如何读取字节数组中的前3个字节

问题描述:

我有字节数组,我只需要读取前3个字节不多。如何读取字节数组中的前3个字节

C#4.0

+0

这是作业,不是吗? – Narazana 2010-09-24 08:02:15

如何:

Byte byte1 = bytesInput[0]; 
Byte byte2 = bytesInput[1]; 
Byte byte3 = bytesInput[2]; 

或阵列:

Byte[] threeBytes = new Byte[] { bytesInput[0], bytesInput[1], bytesInput[2] }; 

或者:

Byte[] threeBytes = new Byte[3]; 
Array.Copy(bytesInput, threeBytes, 0, 3); 
    // not sure on the overload but its similar to this 

任何这些够吗?

IEnumerable<byte> firstThree = myArray.Take(3); 
byte[] firstThreeAsArray = myArray.Take(3).ToArray(); 
List<byte> firstThreeAsList = myArray.Take(3).ToList(); 

简单for循环也可以做这项工作。

for(int i = 0; i < 3; i++) 
{ 
    // your logic 
} 

或者只是在数组中使用索引。

byte first = byteArr[0]; 
byte second = byteArr[1]; 
byte third = byteArr[2]; 

byte b1 = bytearray[0]; 
byte b2 = bytearray[1]; 
byte b3 = bytearray[2]; 

阵列从0索引,所以第3个字节是在阵列中的0,1和2个时隙。