简体   繁体   中英

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?

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;

但是viator emptor得到的字节顺序会随着字节顺序而变化。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM