Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# int to byte[]

I need to convert an int to a byte[] one way of doing it is to use BitConverter.GetBytes(). But im unsure if that matches the following specification:

An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows:

Source: RFC1014 3.2

How could i do a int to byte transformation that would satisfy the above specification?

like image 357
Peter Avatar asked Aug 23 '09 16:08

Peter


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


2 Answers

The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.

Now, you are most probably working on a little-endian machine and BitConverter.GetBytes() will give you the byte[] reversed. So you could try:

int intValue; byte[] intBytes = BitConverter.GetBytes(intValue); Array.Reverse(intBytes); byte[] result = intBytes; 

For the code to be most portable, however, you can do it like this:

int intValue; byte[] intBytes = BitConverter.GetBytes(intValue); if (BitConverter.IsLittleEndian)     Array.Reverse(intBytes); byte[] result = intBytes; 
like image 105
paracycle Avatar answered Sep 20 '22 16:09

paracycle


Here's another way to do it: as we all know 1x byte = 8x bits and also, a "regular" integer (int32) contains 32 bits (4 bytes). We can use the >> operator to shift bits right (>> operator does not change value.)

int intValue = 566;  byte[] bytes = new byte[4];  bytes[0] = (byte)(intValue >> 24); bytes[1] = (byte)(intValue >> 16); bytes[2] = (byte)(intValue >> 8); bytes[3] = (byte)intValue;  Console.WriteLine("{0} breaks down to : {1} {2} {3} {4}",     intValue, bytes[0], bytes[1], bytes[2], bytes[3]); 
like image 29
Maciek Avatar answered Sep 20 '22 16:09

Maciek