Sunday, April 3, 2011

Cast int to byte[4] in .NET

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

From stackoverflow
  • 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);
    // ...
    
    galets : Good idea! Thank you
  • 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.

    galets : Thanks! I knew there's an easy way to do this :)
  • byte[] bytes = BitConverter.GetBytes(42);

    • 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.
  • 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.

    Gareth Davis : also happens to be cross platform, the above also works in Java :)
    Quintin Robinson : Yeah lol, had to implement a utility class with similar code in Java so I could control byte conversion =P

0 comments:

Post a Comment