O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required