How do I put:
int32_t x = someValue;
Into my char array:
char * msg = new char[65546]();
Any help would be appreciated!
How do I put:
int32_t x = someValue;
Into my char array:
char * msg = new char[65546]();
Any help would be appreciated!
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.
If you want to print the value, why not just do it?
std::cout << "x = " << x << '\n';
char* msg = new char[123];
int32_t x = 123;
int offset = 0;
memcpy(msg + offset, reinterpret_cast<char*>(&x), sizeof(int32_t));