What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.
It's not clear if this is really what you want, but:
int x = yourNumber();
char a = (char)(x & 0xff);
char b = (char)((x >> 8) & 0xff);
char c = (char)((x >> 16) & 0xff);
char d = (char)((x >> 24) & 0xff);
This assumes you want the bytes interpreted as the lowest range of Unicode characters.
Do get the 8-byte-blocks:
int a = i & 255; // bin 11111111
int b = i & 65280; // bin 1111111100000000
Do break the first three bytes down into a single byte, just divide them by the proper number and perform another logical and to get your final byte.
Edit: Jason's solution with the bitshifts is much nicer of course.
Char? Maybe you are looking for this handy little helper function?
Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
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.
Cheers, David
.net uses Unicode, a char is 2 bytes not 1
To convert between binary data containing non-unicode text use the System.Text.Encoding class.
If you do want 4 bytes and not chars then replace the char with byte in Jason's answer
I have tried it a few ways and clocked the time taken to convert 1000000 ints.
Built-in convert method, 325000 ticks:
Encoding.ASCII.GetChars(BitConverter.GetBytes(x));
Pointer conversion, 100000 ticks:
static unsafe char[] ToChars(int x)
{
byte* p = (byte*)&x)
char[] chars = new char[4];
chars[0] = (char)*p++;
chars[1] = (char)*p++;
chars[2] = (char)*p++;
chars[3] = (char)*p;
return chars;
}
Bitshifting, 77000 ticks:
public static char[] ToCharsBitShift(int x)
{
char[] chars = new char[4];
chars[0] = (char)(x & 0xFF);
chars[1] = (char)(x >> 8 & 0xFF);
chars[2] = (char)(x >> 16 & 0xFF);
chars[3] = (char)(x >> 24 & 0xFF);
return chars;
}