Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# store int in byte array

I work on a small project and i need to store 4 int types in a byte array(which will be sent later on a socket).

This is the code:

       int a = 566;          
       int b = 1106;
       int c = 649;
       int d = 299;
        byte[] bytes = new byte[16];

        bytes[0] = (byte)(a >> 24);
        bytes[1] = (byte)(a >> 16);
        bytes[2] = (byte)(a >> 8);
        bytes[3] = (byte)a;

I shifted the bits of the first value,but i'm not sure now how to retrieve it back...doing the reversed process.

I hope my question is clear,if i missed somthing i'll be glad to explain it again. Thanks.

like image 298
Slashy Avatar asked Sep 25 '26 01:09

Slashy


2 Answers

To extract the Int32 back out from the byte array, use this expression:

int b = bytes[0] << 24
      | bytes[1] << 16
      | bytes[2] << 8
      | bytes[3]; // << 0

Here is a .NET Fiddle that demonstrates.

like image 111
Lasse V. Karlsen Avatar answered Sep 26 '26 13:09

Lasse V. Karlsen


Depends on you comment reply, you can do it like this:

int a = 10;
byte[] aByte = BitConverter.GetBytes(a);

int b = 20;
byte[] bByte = BitConverter.GetBytes(b);

List<byte> listOfBytes = new List<byte>(aByte);
listOfBytes.AddRange(bByte);

byte[] newByte = listOfBytes.ToArray();

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!