Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array into Bitset

Tags:

c++

byte

bitset

I have a byte array generated by a random number generator. I want to put this into the STL bitset.

Unfortunately, it looks like Bitset only supports the following constructors:

  1. A string of 1's and 0's like "10101011"
  2. An unsigned long. (my byte array will be longer)

The only solution I can think of now is to read the byte array bit by bit and make a string of 1's and 0's. Does anyone have a more efficient solution?

like image 940
Unknown Avatar asked Apr 02 '09 02:04

Unknown


2 Answers

Something like this?

#include <bitset>
#include <climits>

template<size_t numBytes>
std::bitset<numBytes * CHAR_BIT> bytesToBitset(uint8_t *data)
{
    std::bitset<numBytes * CHAR_BIT> b;

    for(int i = 0; i < numBytes; ++i)
    {
        uint8_t cur = data[i];
        int offset = i * CHAR_BIT;

        for(int bit = 0; bit < CHAR_BIT; ++bit)
        {
            b[offset] = cur & 1;
            ++offset;   // Move to next bit in b
            cur >>= 1;  // Move to next bit in array
        }
    }

    return b;
}

And an example usage:

int main()
{
    std::array<uint8_t, 4> bytes = { 0xDE, 0xAD, 0xBE, 0xEF };
    auto bits = bytesToBitset<bytes.size()>(bytes.data());
    std::cout << bits << std::endl;
}
like image 131
strager Avatar answered Oct 24 '22 08:10

strager


There's a 3rd constructor for bitset<> - it takes no parameters and sets all the bits to 0. I think you'll need to use that then walk through the array calling set() for each bit in the byte array that's a 1.

A bit brute-force, but it'll work. There will be a bit of complexity to convert the byte-index and bit offset within each byte to a bitset index, but it's nothing a little bit of thought (and maybe a run through under the debugger) won't solve. I think it's most likely simpler and more efficient than trying to run the array through a string conversion or a stream.

like image 45
Michael Burr Avatar answered Oct 24 '22 08:10

Michael Burr