Janaka
Janaka

Reputation: 489

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 ?

Upvotes: 0

Views: 1791

Answers (5)

bitmask
bitmask

Reputation: 34628

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>

Upvotes: 0

n4rzul
n4rzul

Reputation: 4078

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.

Upvotes: 1

Prince John Wesley
Prince John Wesley

Reputation: 63698

Print like this:

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

Upvotes: 0

Alexey Malistov
Alexey Malistov

Reputation: 26975

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.

Upvotes: 0

Patrice Bernassola
Patrice Bernassola

Reputation: 14426

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

Upvotes: 0

Related Questions