2016-07-04 46 views
2

我在一個小項目上工作,我需要將4 int類型存儲在字節數組(稍後將在套接字中發送)。C#在字節數組中存儲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; 

我移動的第一個值的位,但我不知道現在該怎麼找回它回來...做的逆轉過程。

我希望我的問題很清楚,如果我錯過了某些事情,我很樂意再次解釋它。 謝謝。

+6

使用'BitConverter.GetBytes(...)'和其他方向使用'BitConverter.ToInt32(...)' –

+0

@x ...但我需要插入4個字節到這個數組中。我編輯過我的問題.'BitConvertor'返回一個新的字節數組,我不想讓它更復雜,併合並兩個4字節[]陣列我會從'BitConvertor.' – Slashy

+0

你的意思是? 'int b = bytes [0] << 24 |字節[1] << 16 |字節[2] << 8 |字節[3]'? –

回答

2

爲了從字節數組提取Int32背出,使用以下表達式:

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

這裏是一個.NET Fiddle演示。

2

取決於你評論的回覆,你可以做這樣的:

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

這正是我不想做的。簡單的位操作或某些東西沒有解決方案嗎? @x ...我也在尋找..效率..這是一個實時的程序..我真的很想使用低級別的東西。 – Slashy

+0

那麼,你想用C/C++的方式做位移嗎? –

+0

移位不僅與c/C++有關.. haha​​ – Slashy

0

可以使用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);