I was wondering if anyone here knows an efficient way to cast an integer to a byte[4]? I'm trying to write an int into MemoryStream, and this thing wants me to give it bytes
+7
A:
Use a BinaryWriter (constructed with your memory stream); it has a write method that takes an Int32.
BinaryWriter bw = new BinaryWriter(someStream);
bw.Write(intValue);
bw.Write((Int32)1);
// ...
Daniel LeCheminant
2009-02-19 16:50:17
Good idea! Thank you
galets
2009-02-19 16:54:01
+14
A:
You can use BitConverter.GetBytes
if you want to convert a primitive type to its byte representation. Just remember to make sure the endianness is correct for your scenario.
Greg Beech
2009-02-19 16:50:46
+6
A:
BinaryWriter
will be the simplest solution to write to a streamBitConverter.GetBytes
is most appropriate if you really want an array- My own versions in MiscUtil (
EndianBitConverter
andEndianBinaryWriter
) give you more control over the endianness, and also allow you to convert directly into an existing array.
Jon Skeet
2009-02-19 16:54:00
+3
A:
You could also do your own shifting! Although i'd use the built in methods figured i'd throw this out there for fun.
byte[] getBytesFromInt(int i){
return new byte[]{
(byte)i,
(byte)(i >> 8),
(byte)(i >> 16),
(byte)(i >> 24)
};
}
Of course then you have to worry about endian.
Quintin Robinson
2009-02-19 17:02:06
Yeah lol, had to implement a utility class with similar code in Java so I could control byte conversion =P
Quintin Robinson
2009-02-19 17:14:29