Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Sign check of bitwise operation

ID: cpp/bitwise-sign-checkKind: problemSecurity severity: Severity: warningPrecision: highTags:   - reliability   - correctnessQuery suites:   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds code that checks the sign of the result of a bitwise operation. Such a check may yield unexpected results. As an example, consider the following code that checks if thenth bit of a variablex is set:

  x & (1 << n) > 0

Ifx is a 32-bit signed integer, the value ofx&(1<<31) is interpreted as a signed number. Ifx is negative (that is, its sign bit is set), andn is 31, thenx&(1<<31) evaluates to0x80000000 (all bits zero except the sign bit). The sign check on this value fails, implying that the 31st bit ofx is unset. This is clearly incorrect.

Recommendation

The above sign check should be rewritten as

  x & (1 << n) != 0

References


[8]ページ先頭

©2009-2025 Movatter.jp