简体   繁体   中英

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 .

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.

Just use reinterpret_cast . Use the data array as if it were an int pointer.

    char data[sizeof(int)];
    *reinterpret_cast<int*>(data) = length;

BTW memcpy is much slower than this, because it copies byte by byte using a loop.
In the case of an integer, this will just be a straightforward assignment.

This is the only way. Theoretically you could use memcpy or reinterpret_cast but you can't due to problems with endians .

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