簡體   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