tags:

views:

180

answers:

6

By default the BinaryWriter class writes int values with the low bits on the left (e.g. (int)6 becomes 06 00 00 00 when the resulting file is viewed in a hex editor). I need the low bits on the right (e.g. 00 00 00 06).

How do I achieve this?

EDIT: Thanks strager for giving me the name for what I was looking for. I've edited the title and tags to make it easier to find.

+2  A: 

You are looking to change the Byte Order (aka Endianness). You want to print out big endian. Not sure how you'd do that in C#, but you can swap your bytes in the integer before sending it to the BinaryWritter class.

You can check the endianness of the current system using System.BitConverter.IsLittleEndian. I am not sure if BinaryWriter uses the system's endianness or little endian for compatibility.

strager
+6  A: 

Jon Skeet has an EndianBitConverter here that should do the job. Just use big/little endian as desired. Alternatively, just shift the data a few times ;-p

        int i = 6;
        byte[] raw = new byte[4] {
            (byte)(i >> 24), (byte)(i >> 16),
            (byte)(i >> 8), (byte)(i)};
Marc Gravell
+6  A: 

Not really a built in way but you can use this: EndianBit*. Thanks to Jon Skeet :P

grepsedawk
Within seconds of eachother; sorry. You've my +1, though ;-p
Marc Gravell
+1  A: 

If you're determined to use something built in, there are a number of overloads of System.Net.IPAddress.HostToNetworkOrder().

These will do what you want because it's overwhelmingly likely that 'host' order is always little-endian, and 'network' order is big-endian, which is what you want.

Bit of a hack to use these though, if you're not doing anything at all to do with networking.

Will Dean
+1  A: 

You could also use the BitConverter to get a byte array, then reverse it. Something like:

Byte[] bytes = BitConverter.GetBytes(number);
Array.Reverse(bytes);

// Then, to write the values you use
writer.Write(bytes);
configurator
A: 

It won't help now, but I created a connect ticket for BinaryReder/Writer to support Bigendian out the box. Go vote for it here.

Martin Brown