Home > Software engineering >  Store a 2byte value in memory location in C
Store a 2byte value in memory location in C

Time:03-25

I am in need of your help in this problem:

I want to store a 2 byte number in a char array I have tried the below 2 logics but both have failed

char buff[10];

char* ptr = buff;

/* I want to store a 2 byte value say 750 Method 1 */

short a = 750; *( ptr)=a; //Did not work got these values in first 2 bytes in buffer: 0xffffffc8 0xffffffef

/* Method 2 */

short *a=750; memcpy( ptr,a,2) // Got segmentation fault

I know I can do this by dividing by 256 but I want to use a simpler method

*ptr =750/256;

*ptr=750%6;

CodePudding user response:

The easiest way is simply:

uint16_t u16 = 12345;
memcpy(&buff[i], &u16, 2);

memcpy will place the data according to your CPU endianess.

Alternatively you can bit shift, but since bit shifts themselves are endianess-independent, you need to manually pick the correct indices for buff according to endianess.

Memory layout like Little Endian:

buff[i]   = u16 & 0xFFu;
buff[i 1] = (u16 >> 8) & 0xFFu;

Memory layout like Big Endian:

buff[i]   = (u16 >> 8) & 0xFFu;
buff[i 1] = u16 & 0xFFu;

CodePudding user response:

char buff[10];
short a=1023; 

//To store in char array
buff[0] = a & 0xff;
buff[1] = (a >> 8) & 0xff;

// To get original value.
short b = ((buff[1] << 8) & 0xff00) | (buff[0] & 0x00ff);
  • Related