Search code examples
c++stringstream

Why does conversion of int -> hex/oct/bin print as plain decimal value in output?


#include <iostream>
#include <sstream>

using namespace std;

int main() {
     // <variables>
     int t = 0b11011101;

     stringstream aa;

     int n;
     string hexed;
     int hexedNot;
     // </variables>

     aa << t;
     aa >> n;
     cout << n << endl; // output 221
     aa.clear();

     aa << hex << n;
     aa >> hexed;
     aa.clear();

     aa << hex << n;
     aa >> hexedNot;
     cout << hexed << endl; // output dd

     cout << hexedNot; // output 221

     return 2137;
}

I want to convert int decimals to hex/oct/bin ints with stringstream, but I don't know how to approach it properly. If I try to convert it to a string containing hex, it's fine, but when I try to do the same with an integer, it just doesn't work. Any ideas? I can't use c++11 and I want to do it in a really slim and easy way.

I know that I can use cout << hex << something;, but that would just change my output and it wouldn't write the hexified value into my variable.


Solution

  • The std::string hexed; was read from the std::stream, where you read after injecting a hexadecimal representation of n to the stream:

     aa << hex << n;
    

    The next operation

     aa >> hexed;
    

    reads from the stream to the std::string variable. Hence

    cout << hexed << endl; // output dd
    

    You seem to have a big misconception:

    I know that I can use cout << hex << something;, but that would just change my output and it wouldn't write the hexified value into my variable.

    There's no thing like "hexified value" in c++ or any other programming languages. There are just (integer) values.

    Integers are integers, their representation in input/output is a different kettle of fish:

    It's not bound directly to their variable type or what representation they were initialized from, but what you tell the std::istream/std::ostream to do.

    To get the hexadecimal representation of 221 printed on the terminal, just write

    cout << hex << hexedNot;
    

    As for your comment:

    but I want to have a variable int X = 0xDD or int X = 0b11011101 if that's possible. If not, I'll continue to use the cout << hex << sth; like I always have.

    Of course these are possible. Rather than insisting of their textual representation you should try

    int hexValue = 0xDD;
    int binValue = 0b11011101;
    if(hexValue == binValue) {
        cout << "Wow, 0xDD and 0b11011101 represent the same int value!" << endl;
    }