tags:

views:

244

answers:

5

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
Good idea! Thank you
galets
+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
Thanks! I knew there's an easy way to do this :)
galets
+2  A: 

byte[] bytes = BitConverter.GetBytes(42);

Samuel
+6  A: 
  • BinaryWriter will be the simplest solution to write to a stream
  • BitConverter.GetBytes is most appropriate if you really want an array
  • My own versions in MiscUtil (EndianBitConverter and EndianBinaryWriter) give you more control over the endianness, and also allow you to convert directly into an existing array.
Jon Skeet
+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
also happens to be cross platform, the above also works in Java :)
Gareth Davis
Yeah lol, had to implement a utility class with similar code in Java so I could control byte conversion =P
Quintin Robinson