简体   繁体   中英

c++ std::cout in hexadecimal

I have an output statement with printf in C++ that looks like this:

for(int i=0; i<6; i++)
        printf("%.2X", (unsigned char) iter->hwaddress[i]);

I need to do the output with std::cout , I have tried to do it like this:

for(int i=0; i<6; i++)
   cout << hex << (unsigned char) iter->hwaddress[i];

but that just gives me:

  �:�:w:�:�:

Does anyone know how to do this?

You need to cast it to an `int:

char c = 15;
cout << hex << setfill('0') << setw(2) << static_cast<int>(c); // prints "0f"

hex only affects integer I/O, which char isn't considered part of - so your code ends up still outputting the actual char s.

Note that if char is signed and you need this to work on values larger than 0x7f , you will have to cast it first to unsigned char and then to unsigned int :

cout << hex << setfill('0') << setw(2)
     << static_cast<unsigned int>(static_cast<unsigned char>(c));

If the values of those iter->hwaddress[i] are hardware addresses, why don't you (reinterpret_)cast them to actual pointers? Then cout will print them in hex without any additional effort.

cout << reinterpret_cast<void*>(iter->hwaddress[i]);

It is not clear if you need fixed number of digits. This may require some tools in <iomanip> .

Don't cast to unsigned char but to an integer.

#include <iostream>
#include <iomanip>
#include <cstdio>

int
main()
{
  char numbers[] = {1, 2, 3, 4, 5, 6};
  // Using C-style printf:    
  for (int i = 0; i < 6; i++)
    std::printf("%02X", static_cast<unsigned>(numbers[i]));
  printf("\n");
  // Using C++ streams:
  for (int i = 0; i < 6; i++)
    std::cout << std::hex << std::setw(2) << std::setfill('0')
              << static_cast<unsigned>(numbers[i]);
  std::cout << std::endl;
}

The << operator is overloaded on these types. Also avoid C-style casts in favor of static_cast if you need to cast at all.

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