简体   繁体   中英

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);

}

I used above code segment to print the hex value of each byte of a Integer. But that is not working properly. What is issue here?

Try something like this:

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);
}

or perhaps:

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

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

for the second example see: http://msdn2.microsoft.com/en-us/library/de8fssa4(VS.80).aspx

Hope this helps.

If you are serious about the , this is how I would suggest to do it.

#include <sstream>

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

Which you may invoke as intToStr(1231212) . If you insist on getting a char array (I strongly suggest you use std::string ), you can copy the c_str() result over:

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

Just use the sprintf function. You will get a char*, so you have your array. See the example on the webpage

Your code looks awful. That's it.

memcpy(pDVal, &x, 4);

What is pDVal ? Why do you use 4? Is it sizeof(int) ?

int iDSize = sizeof(double);

Why sizeof(double) ? May be you need sizeof(int) .

memcpy(&c, &(pDVal[i]), 1); makes copy first byte of i-th array pDVal element.

printf("%d|\n", c); is not working because "%d" is waiting integer.

Print like this:

printf("%d|\n", c & 0xff);
printf("%x|\n", c & 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