我正在解析作为字节数组输入的文件中的二进制数据。我试图将数组的底层二进制分解为“word”(每10或12位)。我有一个函数来完成这个任务,但是由于我处理了大量的数据,所以非常耗时。我有有限的编程经验,所以我相信有更好的方法来完成这一点。
private void separateWords(List<byte[]> minorFrames, int wordSize, int frameLength)
{
UInt16[] wordArray = new UInt16[frameLength];
foreach (byte[] array in minorFrames)
{
// Convert byte array to bit array
// Bits need to be reversed on a byte boundary
byte[] temp = new byte[array.Length];
for (int i = 0; i < array.Length; i++)
{
temp[i] = ReverseBits(array[i]);
}
BitArray binaryArray = new BitArray(temp);
for (int i = 0; i < (binaryArray.Length / wordSize); i++ )
{
UInt16 newWord = 0;
for (int j = 0; j < wordSize; j++)
{ // Converts every n bits to UInt16
if (binaryArray[j + (i*wordSize)])
newWord += Convert.ToUInt16(Math.Pow(2, ((wordSize-1)-j)));
}
wordArray[i]=newWord; // Populate formatted minor frame
}
words.Add(wordArray); // add populated minor frame to lsit
}
}理想情况下,我希望直接对字节数组进行操作。“words”将被保存到into 16中,以保持输出尽可能小。
我目前的想法是:
不过,我在将位转换为UInt16时遇到了一些困难,并且不确定如何转换整个数组。也许有更好的方法来解决这个问题?
发布于 2020-07-29 16:27:37
Math.Pow非常耗时。考虑使用按位和移位运算符(C#参考)。
if (binaryArray[j + i * wordSize]) {
newWord |= (ushort)(1 << (wordSize - 1 - j));
}发布于 2020-07-29 18:08:42
在得到一些反馈后,我将循环重写为:
public List<UInt16[]> separateWords(List<byte[]> minorFrames, int wordSize, int frameLength)
{
List<UInt16[]> framedWords = new List<UInt16[]>();
UInt16 newWord = 0;
foreach (byte[] array in minorFrames)
{
int bitcount = 1;
int wordCount = 0;
BitArray binaryArray = new BitArray(array);
UInt16[] wordArray = new UInt16[frameLength];
for (int i = 1; i <= array.Length; i++)
{
for (int j = 1; j <= 8; j++)
{
newWord <<= 1; // Make room for next bit
newWord |= Convert.ToUInt16(binaryArray[(i * 8) - j]); // Adds next bit in array
if (bitcount % wordSize == 0) // Only if multiple of wordsize
{
wordArray[wordCount] = newWord; // Populate formatted minor frame
newWord = 0; // Reset for next word
wordCount++; // Advance index
}
bitcount++;
}
}
framedWords.Add(wordArray); // add populated minor frame to lsit
}
return framedWords;
}运行时间从12分钟延长到2.5分钟。
https://stackoverflow.com/questions/63157787
复制相似问题