简体   繁体   English

C ++任何hex到char

[英]C++ any hex to char

Is there a better way from hex to char? 从十六进制到char有更好的方法吗?

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

(asking because of this --> C++ using pointers, nothing is passed ) (因为这个问题 - > 使用指针的C ++,没有通过

Also is there a fast way to make a char array out of hex values (eg. 0x12345678 to a char array)? 还有一种快速方法可以使用十六进制值(例如0x12345678到字符数组)来生成char数组吗?

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. STL为“索引成char数组”技巧致记。

Also beware when printing char s, which are signed on some platforms. 打印char时也要注意,这些char在某些平台上签名。 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)); 如果你想128打印为80而不是FFFFFFFF ,你必须通过先转换为unsigned char来防止它被视为-1hexify((unsigned char)(c));

What do you intend to be stored in the variable one ? 你有什么打算被存储在变量one

The code as written will store the ASCII character 0x01 into one . 写入的代码将ASCII字符0x01存储为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: 如果您正在寻找数字 1,那么您需要明确说出:

char one = '1';

That stores the actual character, not the ASCII code 0x01 . 它存储实际字符,而不是ASCII代码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. 相反,如果您试图将32位整数视为4个字节的序列,每个字节都是ASCII字符,则这是另一回事。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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