简体   繁体   中英

Cast int into an array of two bytes

I'm a Java programmer and I tried to use two different way of printing bytes into stdout.

unsigned char bytes[2];
//...
printf("%x%x", bytes[0], bytes[1]);
std::cout << bytes[0] << bytes[1];

But the output of these methods is different. Why? How to make printf output the same as with std::cout ?

With std::cout they will be printed as characters.

With printf integer promotion occurs and they get passed as int s, and the %x specifier tells printf to print an unsigned int in hexadecimal format.

You can get printf to print a character by using %c , or you can get std::cout to print it as hex by doing the promotion yourself and setting the hex flag:

std::printf("%c%c", bytes[0], bytes[1]);
std::cout << std::hex << +bytes[0] << +bytes[1];

%x outputs a number in a hexadecimal CS, for example, code

int x = 80;
printf("%x", x);

will print 50 .

To write numbers in decimal form, you have to use %d . Also, to print char variable in a form of a number, not character, you have to cast it to int :

unsigned char bytes[2];
//...
printf("%d%d", bytes[0], bytes[1]);
std::cout << (int)bytes[0] << (int)bytes[1];

The equivalent would be :

#include <iomanip>  // needed for std::hex

std::cout << std::hex << static_cast<unsigned int>(bytes[0]) << static_cast<unsigned int>(bytes[1]);

Two differences :

  • your printf with %x prints in hexadecimal - for C++ streams, there's std::hex for that
  • your printf takes int values (for %x ), but C++ streams don't have an operator<< that prints a unsigned char as an integer value (instead it'll be printed as a character), so you need to cast the unsigned char to an integer type first (eg. unsigned int as in the code above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM