Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 734
Kacper Fałat Avatar asked Oct 21 '13 14:10

Kacper Fałat


People also ask

How do I convert an int to a char?

We can also convert int to char in Java by adding the character '0' to the integer data type. This converts the number into its ASCII value, which after typecasting gives the required character.

Can we store integer in char array?

You can add the ASCII value of 0 to the value you want to store digit into the character array. For example if you want to store 0,1,...,9 into the character array A[10], you may use the following code. This works only if the integer you want to store is less than 10.

How do I convert an int to a char in c?

A char in C is already a number (the character's ASCII code), no conversion required. If you want to convert a digit to the corresponding character, you can simply add '0': c = i +'0'; The '0' is a character in the ASCll table.


2 Answers

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.

like image 189
Rahul Tripathi Avatar answered Sep 30 '22 02:09

Rahul Tripathi


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.

like image 35
Yochai Timmer Avatar answered Sep 30 '22 00:09

Yochai Timmer