Copy short int to char array

I have a short integer variable named s_int that contains value = 2

unsighed short s_int = 2;

I want to copy this number into a char array at the first and second position of the char array.

Say we have char buffer[10];. We want two bytes to s_intbe copied to buffer[0]and buffer[1].

How can i do this?

+3
source share
5 answers

The usual way to do this would be to use bitwise operators to slice and copy it, bytes at a time:

b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;

although it really should be done in unsigned char, and not in the usual char, as they are signed on most systems.

.

+10

*((short*)buffer) = s_int;

viator emptor, endianness.

+6

.

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];
+3

memcpy, -

memcpy(buffer, &s_int, 2);

, , unsigned short *, s_int . , lsb msb. , , sizeof (short) 2.

+2

,

char* where = (char*)malloc(10);
short int a = 25232;
where[0] = *((char*)(&a) + 0);
where[1] = *((char*)(&a) + 1);
0

Source: https://habr.com/ru/post/1748036/


All Articles