来自 int 数字的十六进制 *char

Hex *char from int number

我在这里问如何将 4 个字符转换为整数:

它正在工作,但现在我需要做同样的事情,但相反。我想从一个整数中生成 4 个字符。因为我不理解在实践中完全移位和使用 OR 和 AND 运算符,所以我尝试用愚蠢的解决方案来解决我的问题,比如先将 int 转换为 Hex String,然后再转换为 char,等等。有人能帮我解决这个问题吗?对不起我的英语。

这里可能是一个可以接受的解决方案,操纵指针。可以找到关于指针的优秀教程 here

int main()
    {
      int test32 = 0 ;
      int* ptest32 = &test32;

      char* p1st8bits = (char*) ptest32;
      char* p2nd8bits = p1st8bits + 8;
      char* p3nd8bits = p1st8bits + 16;
      char* p4nd8bits = p1st8bits + 24;

      std::cout  <<"first 8 bits: " << *p1st8bits << "\n" ;
      std::cout  <<"second 8 bits: " << *p2nd8bits << "\n" ; 
      std::cout  <<"third 8 bits: " << *p3nd8bits << "\n" ;
      std::cout  <<"fourth 8 bits: " << *p4nd8bits << "\n" ;
    }

试试这个:

const unsigned int value = 0x12345678;
std::ostringstream hex_stream;
hex_stream << hex << value;

以上片段会将值转换为十六进制字符串。以下代码段将每行打印一个字符。

std::string chars_as_hex = hex_stream.str();
for (i = 0; i < chars_as_hex.length(); ++i)
{
  std::cout << chars_as_hex[i] << std::endl;
}

I need to do the same but in reverse. I want to make 4 chars from one int.

反向操作即可。向右移动而不是向左移动,并在移动后而不是移动前屏蔽:

char bytes[4];
long number = 0x00000190L; // int may be only 2 bytes on some implementations
for(int i = 0; i < 4; i++) {
    bytes[i] = (number >> (8 * i)) & 0xFFL;
}

如果您的目的是获取十六进制字符串(如标题所示,但不是链接问题的反面),那么最简单的做法是使用 std::hex 和一个流.

使用位移:

#include <string>
#include <iostream>


void main(void* args)
{
  // 4 byte integer
  unsigned int charInteger = 0;

  // 4 characters
  unsigned char c1 = 'a';
  unsigned char c2 = 'b';
  unsigned char c3 = 'c';
  unsigned char c4 = 'd';

  // put each character above into each byte of a 4 byte integer
  charInteger = (c1 & 0xFF)
       | ((c2 & 0xFF) << 8) 
       | ((c3 & 0xFF) << 16)
       | ((c4 & 0xFF) << 24);

  std::cout << "charInteger = " << charInteger << "\n";

  // get each byte of the integer
  unsigned int i1 = charInteger & 0xff; // first byte
  unsigned int i2 = (charInteger >> 8) & 0xff; // second byte
  unsigned int i3 = (charInteger >> 16) & 0xff; // third byte
  unsigned int i4 = (charInteger >> 24) & 0xff; // fourth byte

  // display each byte of charInteger as characters
  std::cout << char(i1) << "\n";
  std::cout << char(i2) << "\n";
  std::cout << char(i3) << "\n";
  std::cout << char(i4) << "\n";

  std::string h;
  std::cin >> h;
}

这应该可以完成工作:

const char* chars = (const char*)&number;

现在您可以访问数组中的字符了:

chars[0], chars[1], chars[2], chars[3]

实际上你可以反过来做:

char chars[4];
// write each char in to array
int *pnumber = (int*)chars;
// now you can read the number: 
int number = (*pnumber);

此处的顺序很重要,它取决于您系统的字节顺序。