Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout hex format

Tags:

c++

i am a c coder, new to c++.

i try to print the following with cout with strange output. Any comment on this behaviour is appreciated.

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<x<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}

output:

 Value of x  ÿ  hexadecimal
 Value of x ff by printf
like image 899
pdk Avatar asked Aug 29 '10 14:08

pdk


People also ask

How do you write Hex in C++?

Hexadecimal uses the numeric digits 0 through 9 and the letters 'a' through 'f' to represent the numeric values 10 through 15). Each hex digit is directly equivalent to 4 bits. C++ precedes a hexadecimal value that it prints with the characters "0x" to make it clear that the value is in base 16.

What is std :: hex in C++?

std::hex : When basefield is set to hex, integer values inserted into the stream are expressed in hexadecimal base (i.e., radix 16). For input streams, extracted values are also expected to be expressed in hexadecimal base when this flag is set.

What is hexadecimal code?

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.


2 Answers

<< handles char as a 'character' that you want to output, and just outputs that byte exactly. The hex only applies to integer-like types, so the following will do what you expect:

cout << "Value of x  " << hex << int(x) << "  hexadecimal" << endl;

Billy ONeal's suggestion of static_cast would look like this:

cout << "Value of x  " << hex << static_cast<int>(x) << "  hexadecimal" << endl;
like image 80
Thanatos Avatar answered Nov 01 '22 17:11

Thanatos


You are doing the hex part correctly, but x is a character, and C++ is trying to print it as a character. You have to cast it to an integer.

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<static_cast<int>(x)<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}
like image 31
Starkey Avatar answered Nov 01 '22 16:11

Starkey