简体   繁体   English

使用按位运算符从32位整数检索字节

[英]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: ! getByte - 从字x中提取字节n从0(LSB)到3(MSB)编号的字节示例:getByte(0x12345678,1)= 0x56法律操作:! ~ & ^ | 〜&^ | + << >> Max ops: 6 Rating: 2 + << >> Max ops:6评级: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. 你的移位没有任何意义 - 首先,你向左移动(24 - 8n)位,然后向右移动8n位。 Why? 为什么? Also, it's wrong. 而且,这是错的。 If n is 0, you shift x left by 24 bits and return that value. 如果n为0,则将x向左移位24位并返回该值。 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 ). 不允许使用运算符-尤其是*是一个问题(不能做* 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. 不完全漂亮,但它符合问题描述:6个操作员,所有这些都是合法的。

EDIT: Just had a (pretty obvious) idea for how to avoid * 8 编辑:刚才有一个(非常明显的)如何避免* 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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