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
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With