copying a short int to a char array

cateof picture cateof · Jun 1, 2010 · Viewed 32.8k times · Source

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?

Answer

crazyscot picture crazyscot · Jun 1, 2010

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.