使用按位运算符从32位整数检索字节 [英] retrieve byte from 32 bit integer using bitwise operators
问题描述
下面是什么问题,我现在有,我只是不明白它是如何错...
了getByte - 提取字节n词从X字节从0(LSB)编号为
3(MSB)的例子:了getByte(0x12345678,1)= 0x56法律OPS! 〜&安培;
^ | + LT;< >>最大OPS:6评级:2
块引用>INT了getByte(INT X,INT N){
返回((X LT;≤(24 - 8 * n))的>>(8 * n)的);
}
解决方案您移动没有任何意义 - 首先,你转移由(24 - 8N)左位,然后通过8N位移回右。为什么?此外,这是错误的。如果n是0,则移位通过24位左x和返回该值。试着用笔和纸来看看,这是完全错误的。
正确的做法是做:
INT了getByte(INT X,INT N){
则返回(x>→8 * N)及0xFF的;
}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; }
这篇关于使用按位运算符从32位整数检索字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!