简体   繁体   中英

BitArray to ByteArray not returning correct byte data

I have a bit array that i am trying to convert to a byte array. But am having a difficult time working out the correct logic for it.

This is my bit array data:

1111 11111111 11111111 11111111 11101101

With an end result of:

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

This is clearly not right but just can't figure out the right logic at this point.

This is my method in my bitstream class:

    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
            }
        }
    }

Can any one see where my logic is going wrong here?

You could just use BitArray.CopyTo :

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

Reference: https://stackoverflow.com/a/20247508

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM