简体   繁体   English

从字节数组中获取最后一个字节

[英]Get last bytes from byte array

I need to read last 8 bytes from byte array.我需要从字节数组中读取最后 8 个字节。 Right now im doing it like this:现在我这样做:

last8 = data.Reverse().Take(8).Reverse();

Is there any better way of doing this?有没有更好的方法来做到这一点?

Use Array.Copy for example:使用Array.Copy例如:

byte[] data = ...;
byte[] last8 = new byte[8];
Array.Copy(data, data.Length-8, last8, 0, 8);

What about this:那这个呢:

var last8 = data.Skip(data.Length - 8);

Would save the step of reversing an array twice.将节省两次反转数组的步骤。

您还可以使用data.Skip(data.Count - 8) (如果您的数据已经被枚举 - 例如一个ArrayList )。

C# 8 has a new feature that might help ... C# 8 有一个新功能可能有助于...

var myByteArray = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A };
byte[] last8 = mydata[^8..];   //      => 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A

In the above, we start at "8 from the end" then go to the end.在上面,我们从“8 from the end”开始,然后走到最后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM