2017-10-05 42 views
-1

我有一个位数组,我试图转换为一个字节数组。但是我很难为它制定正确的逻辑。BitArray到ByteArray没有返回正确的字节数据

这是我的位数组数据:

1111 11111111 11111111 11111111 11101101 

随着最终结果:

[0]: 00011010 //this is obviously wrong should be: 11101101 
[1]: 11111111 
[2]: 11111111 
[3]: 11111111 
[4]: 11111111 // also obviously wrong should be :00001111 

这显然是不对的,但就是不能在这一点上找出正确的逻辑。

这是我的方法,我的比特流类:

public void GetByteArray(byte[] buffer) 
    { 
     //1111 11111111 11111111 11111111 11101101 
     int totalBytes = Mathf.CeilToInt(Pointer/8f); 
     int pointerPos = Pointer - 1; // read back should not change the current bitstream index 

     for (int i = totalBytes-1; i >= 0; --i) 
     { 
      int counter = 0; // next byte when == 8 

      for (int j = pointerPos; j >= 0; --j) 
      { 
       counter++; 
       pointerPos--; 

       if (BitArray[j]) // if bit array [j] is true then `xor` 1 
        buffer[i] |= 1; 

       // we don't shift left for counter==8 to avoid adding extra 0 
       if (counter < 8) 
        buffer[i] = (byte)(buffer[i] << 1); 
       else 
        break; //next byte 
      } 
     } 
    } 

任何一个能看到我的逻辑是怎么回事错在这里?

回答

1

你可以只使用BitArray.CopyTo

byte[] bytes = new byte[4]; 
ba.CopyTo(bytes, 0); 

参考:https://stackoverflow.com/a/20247508

+0

啊该死这就是尴尬,浪费时间在这让它在一条线路来提供。大声笑感谢。有没有办法看到CopyTo的源代码,我很好奇他们是如何做到的,所以我可以看到我出错的地方。 – Sir

+0

谷歌是你的朋友:)。 – NightOwl888

+1

下面是它如何在.NET Core中实现的:https://github.com/dotnet/corefx/blob/master/src/System.Collections/src/System/Collections/BitArray.cs#L509,这里是。 NET框架:http://www.dotnetframework.org/default.aspx/DotNET/DotNET/[email protected]/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/Collections/[email protected]/1/BitArray @cs – NightOwl888