繁体   English   中英

如何将 integer 转换为字符数组

[英]How to Convert integer to char array

int x = 1231212;
memcpy(pDVal, &x, 4);
int iDSize = sizeof(double);
int i = 0;
for (; i<iDSize; i++)
{
    char c;
    memcpy(&c, &(pDVal[i]), 1);
    printf("%d|\n", c);
    printf("%x|\n", c);

}

我使用上面的代码段来打印 Integer 的每个字节的十六进制值。 但这不能正常工作。 这里有什么问题?

尝试这样的事情:

void Int32ToUInt8Arr( int32 val, uint8 *pBytes )
{
  pBytes[0] = (uint8)val;
  pBytes[1] = (uint8)(val >> 8);
  pBytes[2] = (uint8)(val >> 16);
  pBytes[3] = (uint8)(val >> 24);
}

也许:

UInt32 arg = 18;
array<Byte>^byteArray = BitConverter::GetBytes( arg);
// {0x12, 0x00, 0x00, 0x00 }

byteArray->Reverse(byteArray);
// { 0x00, 0x00, 0x00, 0x12 }

对于第二个示例,请参阅: http://msdn2.microsoft.com/en-us/library/de8fssa4(VS.80).aspx

希望这可以帮助。

如果您对很认真,我建议您这样做。

#include <sstream>

template <typename Int>
std::string intToStr(Int const i) {
  std::stringstream stream;
  stream << std::hex << i;
  return stream.str();
}

您可以调用intToStr(1231212) 如果您坚持要获取一个char数组(我强烈建议您使用std::string ),您可以将c_str()结果复制到:

std::string const str = intToStr(1231212);
char* const chrs = new char[str.length()+1];
strcpy(chrs,str.c_str()); // needs <string.h>

只需使用sprintf function。 你会得到一个 char*,所以你有你的数组。 请参阅网页上的示例

你的代码看起来很糟糕。 而已。

memcpy(pDVal, &x, 4);

什么是pDVal 你为什么用4? sizeof(int)吗?

int iDSize = sizeof(double);

为什么sizeof(double) 可能你需要sizeof(int)

memcpy(&c, &(pDVal[i]), 1); 复制第 i 个数组 pDVal 元素的第一个字节。

printf("%d|\n", c); 无法正常工作,因为“%d”正在等待 integer。

像这样打印:

printf("%d|\n", c & 0xff);
printf("%x|\n", c & 0xff);

暂无
暂无

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

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