Reputation: 18482
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
Upvotes: 4
Views: 683
Reputation: 82345
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.
Upvotes: 3
Reputation: 1500865
BinaryWriter
will be the simplest solution to write to a streamBitConverter.GetBytes
is most appropriate if you really want an arrayEndianBitConverter
and EndianBinaryWriter
) give you more control over the endianness, and also allow you to convert directly into an existing array.Upvotes: 6
Reputation: 136647
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.
Upvotes: 14
Reputation: 51081
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);
// ...
Upvotes: 7