Question

There are two variables,

uint8_t x (8 bit type)
uint16_t y (16 bit type)

, that together hold information about the value of an int num. Say num consists of four bytes abcd (where a is most significant). Then x needs to be copied to b, and y needs to be compied to cd. What is the best way/code to do this?

Was it helpful?

Solution

This works for me:

#include <stdio.h>
#include <stdint.h>

int main()
{
   uint8_t x = 0xF2;
   uint16_t y = 0x1234;
   int a = 0x87654321;

   // The core operations that put x and y in a.
   a = (a & 0xFF000000) | (x<<16);
   a = (a & 0xFFFF0000) | y;

   printf("x: %X\n", x);
   printf("y: %X\n", y);
   printf("a: %X\n", a);
}

Here's the output:

x: F2
y: 1234
a: 87F21234

OTHER TIPS

you can use a union (although be careful with padding/alignment)

typedef union 
{
  uint32_t abcd;
  struct 
  {
    uint8_t a;
    uint8_t b;
    uint16_t cd;
  } parts;
} myvaluetype;

myvaluetype myvalue = {0};
uint8_t x = 42;
uint16_t y = 2311;

myvalue.parts.b = x;
myvalue.parts.cd = y;

printf( "%u\n", myvalue.abcd );

Bytemasks will do. something like below

int8 x = a & 0xff;
int16 y = a & 0xff00;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top