views:

1371

answers:

3

BitConverter.ToUInt16() expects the bytes to be reversed, i guess that's how they are stored in memory. But how can I convert it when it's not reversed, w/o modifying the array?

Byte[] ba = { 0, 0, 0, 6, 0, 0 };
BitConverter.ToUInt16(ba, 2); // is 1536/0x0600, but I want 6/0x0006
A: 

I think your best call would be to reverse the array with Array.Reverse method.

http://msdn.microsoft.com/en-us/library/system.array.reverse(VS.71).aspx

freiksenet
That would reverse the whole array, not just the bytes of each Int16.
Jon B
Jon's right, that's what I was trying to avoid. But thnx for reply!
flamey
+4  A: 

It sounds like you want my EndianBitConverter in MiscUtil, which lets you specify whether you want to use big or little endianness.

Basically it provides the same functionality as BitConverter but as instance methods. You then get the appropriate kind of EndianBitConverter and do what you want with it.

(It provides a bit more functionality for working efficiently with arrays, which may or may not be useful to you.)

The library is open sourced under a fairly permissive licence.

Jon Skeet
fairly permissive meaning "if you want to change this don't, because jon skeet knows your code better than you and has already optimized this for your code" type license?
Darren Kopp
A: 

You can also use IPAddress.HostToNetworkOrder.

Paul Alexander