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?

Recommended Answers

All 6 Replies

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.

commented: I appreciate your knowledge. +13
commented: Great post, keep up the good work Tommy ! :) +21

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?

Yes, If you use the namespace. there is no need to inline the std::

Enquiries about printf function is more of a c question don't you think?

Ok thank you very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.