Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata