Bitwise Operations Full Clean
Bitwise Operations Full Clean
Introduction:
All information stored in a computer's memory is in the form of a series of bits. For example, the
integer 10 (in decimal base) stored as a 16-bit two's complement number will be encoded by the
When we talk about the position of a bit in a binary number, index 0 corresponds to the rightmost bit
(also called Least Significant Bit, or LSB), index 1 to the bit to the left of the lowest bit, and so on.
The leftmost bit of the binary number is called the Most Significant Bit (MSB).
In C language, you can write a number in binary (base 2) by prefixing it with 0b. For example, if we
want to represent the number 26 in binary in eight positions (i.e. 8-bit representation), in C language
this gives 0b00011010. In hexadecimal (base 16), this is equivalent to 0x1A. Recall that, in C
On the other hand, note that on some machines or operating systems, an int could use 2, 4 or 8
bytes (so 16, 32 or 64 bits). Therefore, if we want to declare variables with a determined number of
the desired number of bits regardless of the machine or operating system used.
Bitwise operators:
"Bitwise operators" in C language allow you to set, modify or test one or more bits of data. These
operators are:
NOT "~"
AND "&"
OR "|"
The unary operator NOT flips the state of a bit according to the following table:
ANOT A
01
10
Example:
ABA AND B
000
010
100
111
Example:
OR operator "|"
The binary operator OR combines the state of two bits according to the following table:
ABA OR B
000
011
101
111
Example:
The binary operator XOR combines the state of two bits according to the following table:
ABA XOR B
000
011
101
110
Example:
This operator allows to shift a given operand op_1 by a certain number of bits to the right (the
Example:
This operator allows to shift a given operand op_1 by a certain number of bits to the left.
Example:
Example:
Example:
Example:
puts("bit 2 == 1");
else
puts("bit 2 == 0");