retrieve byte from 32 bit integer using bitwise operators

c

Solution

Your shifting doesn't make any sense - first, you shift left by (24 - 8n) bits, then you shift back right by 8n bits. Why? Also, it's wrong. If n is 0, you shift x left by 24 bits and return that value. Try pen and paper to see that this is entirely wrong.

The correct approach would be to do:

int getByte(int x, int n) {
  return (x >> 8*n) & 0xFF;
}

Problem

Here is the problem and what I currently have, I just don't understand how it is wrong... getByte - Extract byte n from word x Bytes numbered from 0 (LSB) to 3 (MSB) Examples: getByte(0x12345678,1) = 0x56 Legal ops: ! ~ & ^ | + << >> Max ops: 6 Rating: 2 ``` int getByte(int x, int n) { return ((x << (24 - 8 * n)) >> (8 * n)); } ```

Original source