假设我有这个十六进制值:
3FFF
问题表明我必须将其分为两个字节,如下所示: 0011 1111和1111 1111
然后我必须清除每个字节中的最高有效位(MSB),根据我的理解,我必须将最左边的位更改为零,如下所示:
0011 1111和0111 1111 在HEX中是: 3F 7F
然而问题是预期结果应该是: 7F 7F
我错过了什么吗?我想知道预期的结果是错误的还是我遗漏了在清除每个字节中的MSB位时应该做的事情。
答案 0 :(得分:0)
“预期结果”错误。
通过清除一点来获取更高的值是不可能的。†
我没有验证你自己建议的结果,但从表面上看,这对我来说是合乎逻辑的。
† inb4学生指出两个补码的符号位;去吧PLZ!
答案 1 :(得分:0)
使用掩码和逻辑运算:
#include <iostream>
using namespace std;
int main()
{
unsigned char a = 255; // 11111111 // consider your variable is 255
unsigned char LowNibble, HiNibble, tmp = a; // self-explanatory
tmp <<= 4; // discard the high nibble
tmp >>= 4; // storing the low nibble in tmp
LowNibble = tmp; // assigning low nibble to LowNibble
tmp = a; // again for Hi nibble
HiNibble = tmp >> 4; // discard low nibble and storing high nibble in HiNibble
cout << "LowNibble: " << (int)LowNibble << endl; // just for checking
cout << "HiNibble: " << (int)HiNibble << endl;
unsigned char mask = 119; // 01110111 // you said discard the low nibble's highest bit and the high nibble's highest bit so we make a mask of 1s only clear the forth bit of each nibble which is produces in decimal 119
unsigned conc = HiNibble << 4; // assign high nibble to conc
conc |= LowNibble; //putting low nibble in the first bits of con
// now con contains both high and low nibbles
conc &= mask; // clear the highest bit of both two nibbles
cout << (int)conc << endl; //checking
// now dividing again the byte to get what you wanted two nibbles with highest bit cleared:
tmp = conc;
tmp <<= 4;
tmp >>= 4;
LowNibble = tmp;
tmp = conc;
HiNibble = tmp >> 4;
cout << "LowNibble: " << (int)LowNibble << endl;
cout << "HiNibble: " << (int)HiNibble << endl;
cout << endl << endl << endl;
return 0;
}