Posted By

rengber on 02/09/09


Tagged

math utility boolean bitwise Archaeology FoundCode


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Extracting an Int from a Little Endian or Big Endian Byte Array


 / Published in: C#
 

Found this in some code I've been maintaining/expanding. Quite clever.

Picture an array of bytes in binary

00000111 11100000 00000000 00000000

Now picture an Int32 in Binary 00000000000000000000000000000000

To grab a Little Endian Integer (16 bits) out of the array.

Take the second array element 11100000

Assign it to the Int32 variable 00000000000000000000000011100000

Bit shift it up by 8 00000000000000001110000000000000

Now OR it with the first Array element - could also just add.

        00000000000000001110000000000000
or     00000000000000000000000000000111
=      00000000000000001110000000000111

  1. public static Int32 GetInt32(byte[] buffer, int offset, EndianType byteOrder)
  2. {
  3. if (byteOrder == EndianType.LittleEndian)
  4. {
  5. return buffer[offset + 1] << 8 | buffer[offset];
  6. }
  7. else
  8. {
  9. return buffer[offset] << 8 | buffer[offset + 1];
  10. }
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: pckujawa on May 19, 2009

The System.BitConverter class offers methods to get the bytes from any number type as well as convert byte arrays into number types. Unfortunately, it doesn't seem to have the ability to work with Big Endian byte ordering, so you have to do it manually ( if (!BitConverter.IsLittleEndian) byteArray.reverse() ).

You need to login to post a comment.