简体   繁体   中英

retrieve byte from 32 bit integer using bitwise operators

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));
}

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;
}

Unless i am totally mistaken, your code is mathematically incorrect.

getByte(0x000000ff, 0) {
    24 - 8 * n = 24;
    8 * n = 0;
    0x000000ff << 24 = 0xff000000;
    0xff000000 >> 0 = 0xff000000;
    return 0xff000000; // should return 0xff
}

Not being allowed to use operators - and especially * is a problem (can't do * 8 ). I came up with this:

uint8_t getByte (uint32_t x, int n) {
    switch (n) {
        case 0:
            return x & 0xff;
        case 1:
            return (x >> 8) & 0xff;
        case 2:
            return (x >> 16) & 0xff;
        case 3:
            return x >> 24;
    }
}

Not exactly beautiful, but it conforms to the problem description: 6 operators, all of them legal.

EDIT: Just had a (pretty obvious) idea for how to avoid * 8

uint8_t getByte (uint32_t x, int n) {
    return (x >> (n << 3)) & 0xff;
}

I don't understand how your function works. Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM