954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Enquiries on printf function

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?

D.JOHN
Light Poster
39 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

This is a complete explaination of the printf function . you will notice that %x or %X is denoted to show the hexadecimal notation.

Though I am unsure about being able to print out the binary value.

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 
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.

Tom Gunn
Master Poster
733 posts since Jun 2009
Reputation Points: 1,446
Solved Threads: 135
 

I am a bit unclear about this line

std::cout << std::bitset::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
#include
#include
using namespace std; /*<--the thing that i mentioned*/

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

am i correct?

D.JOHN
Light Poster
39 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

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

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 

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

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

Ok thank you very much

D.JOHN
Light Poster
39 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You