flamey
flamey

Reputation: 2379

Converting Byte array to Int-likes in C#

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

Upvotes: 0

Views: 3757

Answers (3)

Paul Alexander
Paul Alexander

Reputation: 32367

You can also use IPAddress.HostToNetworkOrder.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

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.

Upvotes: 4

freiksenet
freiksenet

Reputation: 3679

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

Upvotes: -1

Related Questions