我有 byte[] byteArray,通常是 byteArray.Length = 1-3
我需要将数组分解为位,取一些位(例如,5-17),然后将这些位转换为 Int32。
我试图这样做
private static IEnumerable<bool> GetBitsStartingFromLSB(byte b)
{
for (int i = 0; i < 8; i++)
{
yield return (b % 2 != 0);
b = (byte)(b >> 1);
}
}
public static Int32 Bits2Int(ref byte[] source, int offset, int length)
{
List<bool> bools = source.SelectMany(GetBitsStartingFromLSB).ToList();
bools = bools.GetRange(offset, length);
bools.AddRange(Enumerable.Repeat(false, 32-length).ToList() );
int[] array = new int[1];
(new BitArray(bools.ToArray())).CopyTo(array, 0);
return array[0];
}
Run Code Online (Sandbox Code Playgroud)
但是这个方法太慢了,不得不经常调用。
我怎样才能更有效地做到这一点?
非常感谢!现在我这样做:
public static byte[] GetPartOfByteArray( byte[] …Run Code Online (Sandbox Code Playgroud) 我够大
std::vector<byte> source
Run Code Online (Sandbox Code Playgroud)
我需要从向量中的任何偏移量中获取四个字节(例如,10-13 个字节)并将其转换为整数。
int ByteVector2Int(std::vector &source, int offset)
{
return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24);
}
Run Code Online (Sandbox Code Playgroud)
这种方法太冒犯了,我如何才能以最大的性能做到这一点?