Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying a short int to a char array

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?

like image 896
cateof Avatar asked Jun 01 '10 20:06

cateof


People also ask

How do I copy an int to a char array?

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, ... );

How do I save an int to a char?

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.

How to copy string into char array in C?

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.

How do I copy a char array to another?

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.


2 Answers

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.

like image 108
crazyscot Avatar answered Oct 03 '22 07:10

crazyscot


*((short*)buffer) = s_int;

But viator emptor that the resulting byte order will vary with endianness.

like image 30
James Avatar answered Oct 03 '22 06:10

James