简体   繁体   中英

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?

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

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