DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 16.9 Breaking Up Larger Numbers into Their Equivalent Byte Array Representation

Problem

You have a larger number, such as an integer or a floating-point value, that you want to break up into its equivalent byte array representation. For example, you have the integer value 0x1120FFED and you want to obtain the following byte array: 0x11, 0x20, 0xFF, and 0xED.

Solution

Convert the larger number to a byte*, and operate on the byte* as if it were a pointer to an array of bytes. The following example creates a byte* to an int value and displays each byte value starting with the leftmost byte and working to the right:

unsafe
{
    int myInt = 1;
    byte* myIntPointer = (byte*)&myInt;   // Convert to a byte*

    // Display all bytes of this integer value
    for (int counter = sizeof(int) - 1; counter >= 0; counter--)
    {
        Console.WriteLine(myIntPointer[counter]);
    }
}

The following code shows how this can also be done with a decimal value:

unsafe
{
    decimal myDec = 1M;
    byte* myBytePointer = (byte*)&myDec;   // Convert to a byte*

    // Display all bytes of this decimal value
    for (int counter = sizeof(decimal) - 1; counter >= 0; counter--)
    {
        Console.WriteLine(myBytePointer[counter]);
    }
}

You'll notice that the byte representation for a decimal value (and floating-point values) is quite different from non-floating-point values.

Discussion

When using this technique to extract bytes from a larger number, keep in mind the endianness of the machine you are working on. For example, my Intel machine uses little-endian format, while others may use big-endian format.

With little-endian format, the least-significant byte is stored as the first byte of a 32-bit value, and the most-significant byte is stored as the last byte. It's as if you were reading the bytes backward in memory. Big-endian stores the least-significant byte on the right and the most-significant byte on the left.

On Intel machines, if you want to walk the array starting with the most-significant byte, you must use the following for loop:

for (int counter = sizeof(int) - 1; counter >= 0; counter--)

Notice that the loop starts with the last element of the array and moves toward the first element.

If you want to walk the array starting with the least-significant byte, you would use the following modified for loop:

for (int counter = 0; counter < sizeof(decimal); counter++)

Notice now that the loop starts at the first element in the array and works its way to the last element.

Always determine the endianness of the machine you are working on (consult System.BitConverter.IsLittleEndian) if you are using the code in this recipe. Otherwise, you could make the mistake of looking at the most-significant byte when, in fact, it is the least-significant byte.

See Also

See the "unsafe" keyword in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section