gpt4 book ai didi

c# - 删除字节数组中的前导 0

转载 作者:行者123 更新时间:2023-12-04 04:11:12 28 4
gpt4 key购买 nike

我有一个字节数组如下 -

byte[] arrByt = new byte[] { 0xF, 0xF, 0x11, 0x4 };

所以二进制 arrByt = 00001111 00001111 00010001 000000100

现在我想通过从 arrByt 中删除每个字节的前导 0 来创建一个新的字节数组

arrNewByt = 11111111 10001100 = { 0xFF, 0x8C };

我知道这可以通过将字节值转换为二进制字符串值、删除前导 0、附加值并将字节值转换回新数组来完成。然而,对于大型阵列来说,这是一个缓慢的过程。

有没有更快的方法来实现这一点(比如逻辑运算、位运算或其他高效的方法)?

谢谢。

最佳答案

这应该会很快完成工作。至少只有标准循​​环和运算符。试一试,也适用于更长的源阵列。

// source array of bytes
var arrByt = new byte[] {0xF, 0xF, 0x11, 0x4 };

// target array - first with the size of the source array
var targetArray = new byte[arrByt.Length];

// bit index in target array
// from left = byte 0, bit 7 = index 31; to the right = byte 4, bit 0 = index 0
var targetIdx = targetArray.Length * 8 - 1;

// go through all bytes of the source array from left to right
for (var i = 0; i < arrByt.Length; i++)
{
var startFound = false;

// go through all bits of the current byte from the highest to the lowest
for (var x = 7; x >= 0; x--)
{
// copy the bit if it is 1 or if there was already a 1 before in this byte
if (startFound || ((arrByt[i] >> x) & 1) == 1)
{
startFound = true;

// copy the bit from its position in the source array to its new position in the target array
targetArray[targetArray.Length - ((targetIdx / 8) + 1)] |= (byte) (((arrByt[i] >> x) & 1) << (targetIdx % 8));

// advance the bit + byte position in the target array one to the right
targetIdx--;
}
}
}

// resize the target array to only the bytes that were used above
Array.Resize(ref targetArray, (int)Math.Ceiling((targetArray.Length * 8 - (targetIdx + 1)) / 8d));

// write target array content to console
for (var i = 0; i < targetArray.Length; i++)
{
Console.Write($"{targetArray[i]:X} ");
}

// OUTPUT: FF 8C

关于c# - 删除字节数组中的前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693958/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com