Converting 16-bit integer to 8-bit integer?

Rohith Gowda picture Rohith Gowda · Jun 12, 2013 · Viewed 21.6k times · Source

I'm implementing C code to copy a 16-bit sign and magnitude integer to an 8-bit sign and magnitude integer. Is that even possible? Could someone please explain how to do this?

code snippet:

int16_t a = 0x1234;
int8_t b, c;

How to copy first two digits to variable b and next two digits to variable c?

Answer

user529758 picture user529758 · Jun 12, 2013

You can use the bitwise operators of the language: you need to shift the number 8 and 0 bits to the right to get the first and second digits, respectively (and you should also mask them with 255 so that exactly one byte is extracted):

int16_t i = 0x1234;
uint16_t n = i; // because shifting the sign bit invokes UB
int8_t hi = ((i >> 8) & 0xff);
int8_t lo = ((i >> 0) & 0xff);