Read the byte array representation of a C# base type
March 24, 2015 1 Comment
The BitConverter class has a static GetBytes method that has overloads to accepts all the primitive types in C#: int, long, uint, char, bool, ulong, double, float, short, ushort. The method returns the byte array representation if the supplied primitive type.
Here comes an example:
private static void ReadByteArrayFromTypes() { int value = 15; byte[] bytesOfValue = BitConverter.GetBytes(value); }
You’ll probably know that “int” represents a 32-bit integer i.e. it occupies 32 / 8 = 4 bytes when stored in memory. The total size of the byte array will therefore be 4. “bytesOfValue” will be able to store 15 in the first byte and the others are set to 0:
15
0
0
0
What if we declare 15 as long? Longs are 64-bit integers which take up 64/8 = 8 bytes in memory. In that case “bytesOfValue” will be a byte array of 8 elements where the first 8 bytes are enough to store 15 and the rest will be 0:
15
0
0
0
0
0
0
0
What if we get the byte array representation of a boolean? A boolean can only have two states: true (1) or false (0). The first byte, i.e. 8 bits will be enough to store those states:
private static void ReadByteArrayFromTypes() { bool value = true; byte[] bytesOfValue = BitConverter.GetBytes(value); }
bytesOfValue will therefore be of size 1 whose value will be 0 or 1 depending on the boolean input.
BitConverter also provides a method for the reverse, i.e. convert a byte array back to a primitive type, e.g:
bool value = false; byte[] bytesOfValue = BitConverter.GetBytes(value); bool original = BitConverter.ToBoolean(bytesOfValue, 0);
“original” will be false as expected. The 0 parameter indicates the start index of the array where we want to start reading from it. Normally it’s 0 unless we’re after some other value within the byte array and know where to find it.
View all various C# language feature related posts here.
Reblogged this on .