Bit Manipulation
Addition of Two Numbers
The provided code snippet implements binary addition without using the built-in +
operator.
Identifying Bits Set to 1:
Bitwise AND compares the corresponding bits of
a
andb
.It returns 1 only if the bits in both positions of
a
andb
are 1. Otherwise, it returns 0.
Significance in Carry Calculation:
In binary addition, a carry is generated when adding two bits that are both 1 (e.g., 1 + 1 = 10, where 1 is the carry bit).
The
carry = a & b;
line essentially identifies the positions where botha
andb
have bits set to 1. These positions will generate a carry bit during the addition.
Example:
Let's consider a = 5 (binary: 101)
and b = 3 (binary: 011)
.
a & b = 001
. Here, only the least significant bit (LSB) position has 1s in botha
andb
, indicating a carry will be generated for this bit position.
Using Carry for Addition:
The subsequent line
a = a ^ b;
performs bitwise XOR (^) ona
andb
. XOR is 1 only when the corresponding bits are different.This line effectively adds
a
andb
without considering the carry for the current bit position. The carry will be addressed in the next iteration of the loop.
Carry bit is shifted left
These carry bits are then shifted left in the next line (b = carry << 1;
) to be added in the subsequent bit positions (next bit position) of a
and b
.
Swapping the 2 numbers
Convert Decimal to Binary Conversion
By iterating through each bit position and checking its value using the right shift and bitwise AND operations, the code determines whether each bit in the binary representation of n
is 0 or 1.
Last updated