简体   繁体   中英

How to print all possible unique bit masks of unsigned long long?

Having an unsigned long long how to print it in form of its hex mask into std::string ?

I tried to iterate over binary (values like 0001 , 0010 , 0100 ) mask:

std::stringstream str;
std::string result;
for (unsigned long long mask = 1; mask != 0; mask <<= 1) {
    str << mask;
    str >> result;
    std::cout << result << std::endl;
    str.flush();
}

yet I see only values == 1 (see live sample here ).

So I wonder how to print all possible unique bit masks of unsigned long long ?

You need to use str.clear() , not str.flush() . And see this for the hex part

Having an unsigned long long how to print it in form of its hex mask into std::string ?

You need to use std::hex for printing numbers in hexadecimal base and also note that to reuse the stringstream object you actually need to clear its content by using str() method and also clear the error state flags by calling clear() :

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream str;
    std::string result;
    for (unsigned long long mask = 1; mask != 0; mask <<= 1)
    {
        // retrieve the string:
        str << std::hex << mask;
        str >> result;
        std::cout << result << std::endl;

        // clear the stringstream:
        str.clear();
        str.str(std::string());
    }
}

See How to reuse an ostringstream? :)

every value of a unsigned long long is unique. so iterate over it and have a look at this question Is there a printf converter to print in binary format?

[Edit] Ah I see you only want values with one bit set. Ok do not iterate, shift through it.

You already are iterating those masks, you just have problem to convert them to string:

std::string result;
for (unsigned long long mask = 1; mask != 0; mask <<= 1)
{

    std::stringstream ss;
    ss << std::hex << mask;
    result = ss.str();

    std::cout << result << std::endl;
}

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