当前位置: 动力学知识库 > 问答 > 编程问答 >

bit manipulation - 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.

网友答案:

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.

网友答案:

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();
网友答案:

You can use a MemoryStream to wrap an array of bytes, and then use BinaryWriter to write items to the array, and BinaryReader to read items from the array.

Sample code:

int a = 566;
int b = 1106;
int c = 649;
int d = 299;

// Writing.

byte[] data = new byte[sizeof(int) * 4];

using (MemoryStream stream = new MemoryStream(data))
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(a);
    writer.Write(b);
    writer.Write(c);
    writer.Write(d);
}

// Reading.

using (MemoryStream stream = new MemoryStream(data))
using (BinaryReader reader = new BinaryReader(stream))
{
    a = reader.ReadInt32();
    b = reader.ReadInt32();
    c = reader.ReadInt32();
    d = reader.ReadInt32();
}

// Check results.

Trace.Assert(a == 566);
Trace.Assert(b == 1106);
Trace.Assert(c == 649);
Trace.Assert(d == 299);
分享给朋友:
您可能感兴趣的文章:
随机阅读: