“Use of a signed integer operand with a binary bit

2019-08-29 12:39发布

In the following C snippet that checks if the first two bits of a 16-bit sequence are set:

bool is_pointer(unsigned short int sequence) {
  return (sequence >> 14) == 3;
}

CLion's Clang-Tidy is giving me a "Use of a signed integer operand with a binary bitwise operator" warning, and I can't understand why. Is unsigned short not unsigned enough?

2条回答
你好瞎i
2楼-- · 2019-08-29 13:01

I think the integer promotion causes here the warning. Operands smaller than an int are widened to integer for the arithmetic expression, which is signed. So your code is effectively return ( (int)sequence >> 14)==3; which leds to the warning. Try return ( (unsigned)sequence >> 14)==3; or return (sequence & 0xC000)==0xC000;.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-29 13:04

The code for this check seems to care if either operand to the bitwise operator is signed. It is not sequence causing the warning, but 14, and you can alleviate the problem by making 14 unsigned by appending a u to the end.

(sequence >> 14u)
查看更多
登录 后发表回答