簡體   English   中英

C#將int存儲在字節數組中

[英]C# store int in byte array

我在一個小項目上工作,我需要在字節數組中存儲4個int類型(稍后將在套接字上發送)。

這是代碼:

       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;

我移動了第一個值的位,但現在不確定如何將其取回...執行相反的過程。

我希望我的問題很清楚,如果我錯過了什么,我將很高興再次解釋。 謝謝。

取決於您的評論回復,您可以這樣做:

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

要從字節數組中提取出Int32 ,請使用以下表達式:

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

這是一個演示的.NET Fiddle

您可以使用MemoryStream包裝字節數組,然后使用BinaryWriter將項目寫入數組,並使用BinaryReader從數組中讀取項目。

樣例代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM