如何拆分字节数组 [英] How to split byte array
本文介绍了如何拆分字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须根据0x1E分割字节
I have to split bytes based on 0x1E
byte[] input = { 0x1E, 0x30, 0x30, 0x31, 0x1E };
如何拆分字节数组?
how to split byte array?
推荐答案
尝试下面的代码行。
Hi,
Try with below line of code.
byte[] input = { 0x1E, 0x30, 0x30, 0x31, 0x1E };
List<string> output = new List<string>();
int lastIndex = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ',')
{
if (i - lastIndex == 4)
{
byte[] tmp = { input[i - 4], input[i - 3], input[i - 2], input[i - 1] };
output.Add(BitConverter.ToInt32(tmp, 0));
}
lastIndex = i + 1;
}
}
</string></string>
请参阅以下链接。
http://stackoverflow.com/questions/11816295/splitting-a-字节转换为多字节数组-c-sharp [ ^ ]
试试这个,
Hi,
try this,
static void Main()
{
byte[] arr = { 0x1E, 0x23, 0x1E, 0x33, 0x44, 0x1E };
byte split = 0x1E;
List<byte[]> result = new List<byte[]>();
int start = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == split && i!=0)
{
byte[] _in = new byte[i - start];
Array.Copy(arr, start, _in, 0, i - start);
result.Add(_in);
start = i+1;
}
else if (arr[i] == split && i == 0)
{
start = i + 1;
}
else if (arr.Length - 1 == i && i != start)
{
byte[] _in = new byte[i - start+1];
Array.Copy(arr, start, _in, 0, i - start+1);
result.Add(_in);
}
}
}
--SRJ
--SRJ
感谢大家的回复我已经通过以下yield yield关键字获得了一个样本
Thank u all for reply i have acheived this thru yield keyword below is a sample
class Program
{
static IEnumerable<byte[]> Packetize(IEnumerable<byte> stream)
{
var buffer = new List<byte>();
foreach (byte b in stream)
{
buffer.Add(b);
if (b == 0x1E||b==0x1F||b==0x07)
{
buffer.Remove(b);
yield return buffer.ToArray();
buffer.Clear();
}
}
if (buffer.Count > 0)
yield return buffer.ToArray();
}
static void Main(string[] args)
{
byte[] input = {0x1E, 0x30, 0x30, 0x31, 0x1E, 0x40, 0x41, 0x42, 0x1E, 0x1F };
foreach (var packet in Packetize(input))
{
foreach (var b in packet) Console.Write("{0:x2} ", b);
Console.WriteLine();
}
}
}
这篇关于如何拆分字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文