Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from 32 bit integer to 4 chars

Tags:

c#

encoding

What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.

like image 866
Guille Avatar asked Sep 23 '08 13:09

Guille


People also ask

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

Is a char a byte?

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.

How to convert an integer into a specific byte array in c++?

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.


2 Answers

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.

like image 185
VVS Avatar answered Nov 03 '22 00:11

VVS


Char? Maybe you are looking for this handy little helper function?

Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
like image 37
Sam Avatar answered Nov 02 '22 23:11

Sam