1

How do I put:

int32_t x = someValue;

Into my char array:

char * msg = new char[65546]();

Any help would be appreciated!

CodeDoctorJL
  • 1,216
  • 4
  • 16
  • 29

3 Answers3

3

That entirely depends on the way you want to store the value in the array. If you want to store byte-by-byte you can use the following code:

 int32_t x=someValue;
 char *ptr = (char*)&x;
 char *msg = new char[5];
 for(int i=0;i<4;++i, ++ptr)
    msg[i] = *ptr;

Care should be taken while using the above method. Because some systems use big-endian while the others may use little-endian.

On the other hand, if you want to store digit-by-digit into the char array, use the following:

 int32_t x=someValue;
 int digs[12], count=0;
 char *msg = new char[12];
 while(x>0)
 {
     digs[count++]=x%10;
     x/=10;
 }
 int i=0;
 while(count--)
 {
     msg[i++] = digs[count] +'0';
 }

Either way works. But its better to prefer the second one. Since it is easy to convert back to integer.

nitish712
  • 19,504
  • 5
  • 26
  • 34
2

If you want to print the value, why not just do it?

std::cout << "x = " << x << '\n';
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1
    char* msg = new char[123];
int32_t x = 123;
int offset = 0;
memcpy(msg + offset, reinterpret_cast<char*>(&x), sizeof(int32_t));
TVOHM
  • 2,740
  • 1
  • 19
  • 29
  • Sorry, I just noticed your further comment to your question. If you want to print the value as a string you can easily do this as Joachim suggested, otherwise you could use std::to_string(x) or the itoa function. – TVOHM Sep 18 '13 at 16:56