Kacper Fałat Kacper Fałat - 2 months ago 16
C++ Question

Optimal way to convert an int into a char array

What is the best method (performance) to put an

int
into a
char
array?
This is my current code:

data[0] = length & 0xff;
data[1] = (length >> 8) & 0xff;
data[2] = (length >> 16) & 0xff;
data[3] = (length >> 24) & 0xff;


data
is a
char
array (shared ptr) and
length
is the
int
.

Answer

Are you looking for memcpy

char x[20];
int a;
memcpy(&a,x,sizeof(int));

Your solution is also good as it is endian safe.

On a side note:-

Although there is no such guarantee that sizeof(int)==4 for any particular implementation.