Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top