To all the c++ experts,

I have some doubt on how does the convertion works.

If for instance, I want to convert a hexadecimal eg. 199 to to decimal,

I use printf("%d",199);

but what if I want the hexadecimal 199 to be displayed in binary?

What must is use?

but what if I want the hexadecimal 199 to be displayed in binary?

printf() does not have a conversion to binary. The C++ library has a bitset<> class that will indirectly do it for you, but you need to use cout to print directly, or manually convert to a string for printf():

#include <iostream>
#include <limits>
#include <bitset>

int main()
{
    std::cout << std::bitset<std::numeric_limits<int>::digits>(0x199) << '\n';
}

The other alternative is manually converting the number to a binary string. If you search this forum you can find tons of threads about how to do it that way.

Edited 7 Years Ago by Tom Gunn: n/a

Comments
Great post, keep up the good work Tommy ! :)
I appreciate your knowledge.

I am a bit unclear about this line

std::cout << std::bitset<std::numeric_limits<int>::digits>(0x199) << '\n';

I know that because your do not use the namespace std hence your use std:: to replace it.

But if I am to write in this format:

#include <iostream>
#include <limits>
#include <bitset>
using namespace std; /*<--the thing that i mentioned*/

int main()
{
cout << bitset<numeric_limits<int>::digits>(0x199) << '\n';
}

am i correct?

This question has already been answered. Start a new discussion instead.