crazyCoder
crazyCoder

Reputation: 1582

How to store the contents of a bitset variable to a uint32 in c

I need to find a way to take a sequence of bits in a bit set variable and assign them to a uint32 variable in c++.

For example if I have a bitset<32> variable of "0xffff ffff" I would like to have a uint32 variable of ffff ffff.

I once had the sequence of bits as a string representation but I decided to hold the bits using a bit set. Would it be easier to transfer them from a string?

Upvotes: 3

Views: 4148

Answers (1)

Carl Norum
Carl Norum

Reputation: 224864

bitset has a to_ulong method to do just that:

unsigned long to_ulong() const;
Convert to unsigned long integer
Returns an unsigned long with the integer value that has the same bits set as the bitset.

Example:

#include <bitset>
#include <iostream>

int main(void)
{
    std::bitset<32> b(0xffffffff);
    uint32_t i = b.to_ulong();

    std::cout << b << std::endl;
    std::cout << std::hex << i << std::endl;

    return 0;
}

Build & run:

$ make example && ./example
c++     example.cpp   -o example
11111111111111111111111111111111
ffffffff

Upvotes: 10

Related Questions