Convert from 32 bit integer to 4 characters

What is the best way to split a 32-bit integer into four (unsigned) characters in C #.

+5
source share
7 answers

Quick'n'dirty:

int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
  BitConverter.GetBytes(value).Reverse().ToArray()
));

Converting int to bytes, changing the byte array to the correct order, and then getting the ASCII character representation from it.

EDIT: The inverse method is an extension method from .NET 3.5, for information only. Reverse byte order may also not be needed in your script.

Cheers, David

+7
source

Char? Maybe you are looking for this convenient helper function?

Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
+5
source

, , , :

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);

, .

+4

, 1000000 ints.

, 325000 :

Encoding.ASCII.GetChars(BitConverter.GetBytes(x));

, 100000 :

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 :

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;
}
+4

Get 8 byte blocks:

int a = i & 255; // bin 11111111
int b = i & 65280; // bin 1111111100000000

Break the first three bytes into one byte, just divide them by the desired number and do another logical one and get your last byte.

Edit: Jason's bit rate decision is much better.

0
source

Bitconverter

0
source

.net uses Unicode, a char - 2 bytes, not 1

To convert between binary data containing non-Unicode text, use the System.Text.Encoding class.

If you want 4 bytes, not characters, replace char with a byte in Jason's answer

0
source

All Articles