[英]C#, How to split a byte array by delimiter?
我有一個字節數組,其中包含由','分隔的2字節十六進制數字的集合。 怎么可以用','拆分,然后將數字轉換為整數?
字節數組包含ascii格式的值。
編輯:示例
我的有效字符范圍是0到9,A到F和逗號,所以我的流應該是這樣的
70,67,65,57,44,55,68,66,53,44 ....
這相當於十六進制
FCA9和7DB5
如果您的字節數組是真正的ASCII編碼(每個字符一個字節),那么以下方法將起作用:
int[] ints = Encoding.ASCII.GetString(asciiEncodedBytes).Split(',')
.Select(x => Convert.ToInt32(x,16)).ToArray();
這也將處理混合大小寫和可變長度的十六進制數。
我會將字節數組轉換為字符串,然后使用String.Split(',')
這應該有用,雖然我的C#有點生銹......
byte[] input = { 1, 0, 0, 0, ',', 10, 15, ',', 100, 0, 0, 0, ',' };
List<int> output = new List<int>();
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.