Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

*((short*)buffer) = s_int;

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

By using pointers and casts.

unsigned short s_int = 2;
unsigned char buffer[sizeof(unsigned short)];

// 1.
unsigned char * p_int = (unsigned char *)&s_int;
buffer[0] = p_int[0];
buffer[1] = p_int[1];

// 2.
memcpy(buffer, (unsigned char *)&s_int, sizeof(unsigned short));

// 3.
std::copy((unsigned char *)&s_int,
          ((unsigned char *)&s_int) + sizeof(unsigned short),
          buffer);

// 4.
unsigned short * p_buffer = (unsigned short *)(buffer); // May have alignment issues
*p_buffer = s_int;

// 5.
union Not_To_Use
{
  unsigned short s_int;
  unsigned char  buffer[2];
};

union Not_To_Use converter;
converter.s_int = s_int;
buffer[0] = converter.buffer[0];
buffer[1] = converter.buffer[1];

I would memcpy it, something like

memcpy(buffer, &s_int, 2);

The endianness is preserved correctly so that if you cast buffer into unsigned short *, you can read the same value of s_int the right way. Other solution must be endian-aware or you could swap lsb and msb. And of course sizeof(short) must be 2.

If you don't want to make all that bitwise stuff you could do the following

char* where = (char*)malloc(10);
short int a = 25232;
where[0] = *((char*)(&a) + 0);
where[1] = *((char*)(&a) + 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top