Bitwise Operator On Signed Operand High

Using bitwise operators with signed numbers can lead to unexpected results. It's safer to use them with unsigned numbers.

Detector ID
c/bitwise-operator-on-signed-operand@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1#include <stdio.h>
2
3int bitwiseOperatoronSignedOperandNonCompliant(int i) {
4    // Noncompliant: Bitwise operator applied on signed operand.
5    return 1 << i; // Noncompliant
6}

Compliant example

1#include <stdio.h>
2
3int bitwiseOperatoronSignedOperandCompliant(unsigned int i) {
4    // Compliant: Bitwise operator applied on unsigned operand. 
5    return 1 << i;
6}