使用移位操作仅在一个字节中从右边获取四位
Getting four bits from the right only in a byte using bit shift operations
我想通过仅使用移位操作来尝试只获取一个字节中从右边开始的四位,但它有时有效有时无效,但我不明白为什么。
这是一个例子:
unsigned char b = foo; //say foo is 1000 1010
unsigned char temp=0u;
temp |= ((b << 4) >> 4);//I want this to be 00001010
PS:我知道我可以使用 mask=F
并执行 temp =(mask&=b)
。
移位运算符仅适用于整数类型。使用 <<
会导致隐式整数提升,将 b
类型转换为 int
和 "protecting" 更高位。
求解,使用temp = ((unsigned char)(b << 4)) >> 4;
我想通过仅使用移位操作来尝试只获取一个字节中从右边开始的四位,但它有时有效有时无效,但我不明白为什么。
这是一个例子:
unsigned char b = foo; //say foo is 1000 1010
unsigned char temp=0u;
temp |= ((b << 4) >> 4);//I want this to be 00001010
PS:我知道我可以使用 mask=F
并执行 temp =(mask&=b)
。
移位运算符仅适用于整数类型。使用 <<
会导致隐式整数提升,将 b
类型转换为 int
和 "protecting" 更高位。
求解,使用temp = ((unsigned char)(b << 4)) >> 4;