Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ hex number format

Tags:

c++

hex

I'm trying to output the hex value of a char and format it in a nice way.

Required: 0x01 : value 0x1

All I can get is: 00x1 : value 0x1 // or 0x1 if i don't use iomanip

Here's the code i have, 'ch' was declared to be a unsigned char. Is there any other way to do it other than checking the value and manually add an '0'??

cout << showbase;
cout << hex << setw(2) << setfill('0') << (int) ch;

Edit:

I found one solution online:

cout << internal << setw(4) << setfill('0') << hex << (int) ch
like image 386
cplusplusNewbie Avatar asked Oct 25 '09 00:10

cplusplusNewbie


People also ask

What is 0x in C?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

What is L in C hexadecimal?

L stands for long ; LL stands for long long type. The number does not need to be hex - it works on decimals and octals as well. 3LL // A decimal constant 3 of type long long 03L // An octal constant 3 of type long 0x3L // A hex constant 3 of type long.

What is the format of hexadecimal?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.


1 Answers

std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch;

Since setw pads out to the left of the overall printed number (after showbase is applied), showbase isn't usable in your case. Instead, manually print out the base as shown above.

like image 75
bdonlan Avatar answered Sep 18 '22 10:09

bdonlan