What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.
An int value can be converted into bytes by using the method int. to_bytes().
The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values. The char type can contain both positive and negative values. The range of values is from -128 to 127.
To do this, we use the bitwise AND operator ( & ). We & the value present in each byte by 0xFF which is the hex (16 bit) notation for 255 . This way, we obtain the last 8 bits of our value.
Quick'n'dirty:
int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray()
));
Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.
EDIT: The Reverse
method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.
Char? Maybe you are looking for this handy little helper function?
Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With