简体   繁体   中英

C++ any hex to char

Is there a better way from hex to char?

char one = static_cast<char>(0x01);

(asking because of this --> C++ using pointers, nothing is passed )

Also is there a fast way to make a char array out of hex values (eg. 0x12345678 to a char array)?

You can try this:

std::string hexify(unsigned int n)
{
  std::string res;

  do
  {
    res += "0123456789ABCDEF"[n % 16];
    n >>= 4;
  } while(n);

  return std::string(res.rbegin(), res.rend());
}

Credits to STL for the "index into char array" trick.

Also beware when printing char s, which are signed on some platforms. If you want 128 to print as 80 rather than FFFFFFFF , you have to prevent it from being treated as -1 by converting to unsigned char first: hexify((unsigned char)(c));

What do you intend to be stored in the variable one ?

The code as written will store the ASCII character 0x01 into one . This is a control character, not a printable character. If you're looking for the digit 1, then you need to say so explicitly:

char one = '1';

That stores the actual character, not the ASCII code 0x01 .

If you are trying to convert a number into the string representation of that number, then you need to use one of these mechanisms . If instead, you are trying to treat a 32-bit integer as a sequence of 4 bytes, each of which is an ASCII character, that is a different matter. For that, you could do this:

uint32_t someNumber = 0x12345678;
std::string myString(4, ' ');
myString[0] = static_cast<char>((someNumber >> 24) & 0xFF);
myString[1] = static_cast<char>((someNumber >> 16) & 0xFF);
myString[2] = static_cast<char>((someNumber >> 8) & 0xFF);
myString[3] = static_cast<char>((someNumber) & 0xFF);

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