Search code examples
cpointersmemorytypescasting

Store a 2byte value in memory location in C


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%256;


Solution

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