1

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?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Rohith Gowda
  • 137
  • 2
  • 2
  • 12

1 Answers1

3

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);
  • That would fit all the bits in there, but I would not exactly call the two parts "sign and magnitude integers". Especially the lower half can only be thought of as unsigned. – Thilo Jun 12 '13 at 05:07
  • @Thilo What do you suggest instead? (I realize this may make no sense, but that's because the question isn't quite meaningful either.) –  Jun 12 '13 at 05:10
  • Did not mean to criticize your answer. Just a comment on the question. No other way to fit 16 bits into 2x8. There is no space for an extra sign bit. – Thilo Jun 12 '13 at 05:11
  • @Thilo Of course, I didn't take this as criticism. It's just that I don't have a better idea. –  Jun 12 '13 at 05:13