Question

Sorry if this is hard to understand :P I'm trying to convert a decimal int value to a char value so I can write it in binary mode with fstream in c++. I did this: char hexChar = 0x01; file.write(hexChar, size);. That worked fine until I needed to write a decimal int from user. My question is, how do I convert decimal int to char hex value like this: int decInt = 10; char hexChar = 0x00; hexChar = decInt; file.write(hexChar, size); PS: I've been googling this for about an hour, and haven't found an answer. Every other solved problem with this has been decimal to ASCII hex value like "0A" using cout, not 0x0A using fstream.

Was it helpful?

Solution

It doesn't matter which kind of literal you are using to initialize an int variable

int x = 0x0A;
int y = 10;

The above statements assign the exactly same value to the variables.

To output numeric values with hexadecimal base representation you can use the std::hex I/O stream manipulator:

#include <iostream>
#include <iomanip>


int main() {
    int x = 10; // equivalents to 0x0A
    int y = 0x0A; // equivalents to 10

    std::cout << std::setw(2) << std::setfill('0') 
              << "x = " << std::hex <<  "0x" << x << std::endl;
    std::cout << "y = " << std::dec << y << std::endl;

    return 0;
}

Output:

x = 0xa
y = 10

See the live sample here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top