1

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?

LihO
  • 41,190
  • 11
  • 99
  • 167
DuckQueen
  • 772
  • 10
  • 62
  • 134

3 Answers3

1

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

Community
  • 1
  • 1
Unknown
  • 5,722
  • 5
  • 43
  • 64
1

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? :)

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
0

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.

Community
  • 1
  • 1
Manuel Amstutz
  • 1,311
  • 13
  • 33