I have a short integer variable called s_int that holds value = 2
unsighed short s_int = 2;
I want to copy this number to a char array to the first and second position of a char array.
Let's say we have char buffer[10];
. We want the two bytes of s_int
to be copied at buffer[0]
and buffer[1]
.
How can I do it?
One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );
We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.
Using c_str() with strcpy() A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring.
Use the memmove Function to Copy a Char Array in C It has been implemented as a more robust function to accommodate the case when destination and source memory regions overlap. memmove parameters are the same as memcpy . When copying the arr2 contents, we passed sizeof arr2 expression as the third parameter.
The usual way to do this would be with the bitwise operators to slice and dice it, a byte at a time:
b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;
though this should really be done into an unsigned char
, not a plain char
as they are signed on most systems.
Storing larger integers can be done in a similar way, or with a loop.
*((short*)buffer) = s_int;
But viator emptor that the resulting byte order will vary with endianness.
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