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 byte
s. 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
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.