/ 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.
<pre>
00000000000000001110000000000000
or 00000000000000000000000000000111
= 00000000000000001110000000000111
</pre>
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.
<pre>
00000000000000001110000000000000
or 00000000000000000000000000000111
= 00000000000000001110000000000111
</pre>
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public static Int32 GetInt32(byte[] buffer, int offset, EndianType byteOrder) { if (byteOrder == EndianType.LittleEndian) { return buffer[offset + 1] << 8 | buffer[offset]; } else { return buffer[offset] << 8 | buffer[offset + 1]; } }