Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the system print 0x before the hex number & 0 before the octal number?

Tags:

c++

hex

octal

My teacher says that for the assignment we are not allowed to manually print the 0x before the hex number, we have to make the system do it.

Currently my code looks like this:

cout << "Hex" << setw(12) << hex << static_cast<int>(letter) << setw(12) << hex
        << number << setw(12) << hex << static_cast<int> (symbol) << endl;

It prints the correct hex value but without the 0x.

Additionally, for octal numbers, I have to again, make the system print a 0 before the number (not manually. My code prints correct values, but without the preceding 0:

cout << "Octal" << setw(12) << setbase(8) << static_cast<int>(letter) << setw(12) << setbase(8)
    << number << setw(12) << setbase(8) << static_cast<int>(symbol) << endl;
like image 243
EndlessTilt Avatar asked Sep 22 '19 23:09

EndlessTilt


People also ask

What is the 0x in hex?

The prefix we use for hexadecimal is "0x". To represent the numbers 0-9, we simply use those digits. To represent 10-15, we use the letters A-F.

How do you write hex in C++?

To specify your constant in hex, use a leading 0x , e.g. 0xf . The same thing applies in any other context that can take a (decimal) value - you get hex by using a leading 0x . Or if you want octal for some reason, use a leading 0 , without the x.

What does 0x mean in Python?

If you print a hexadecimal number, Python uses the prefix '0x' to indicate that it's a number in the hexadecimal system and not in the decimal system like normal integers.


1 Answers

Use std::showbase:

std::cout << std::hex << std::showbase << 1234567890;
like image 155
David G Avatar answered Sep 29 '22 10:09

David G