Say I have four 32-bit numbers, defined so that their bits don't overlap, i.e.
unsigned long int num0 = 0xFF000000; unsigned long int num1 = 0x00FF0000; unsigned long int num2 = 0x0000FF00; unsigned long int num3 = 0x000000FF;
Where in each number one could have anything in the place of the FF
s.
Am I right in saying that addition and bitwise or would always produce the same output for such sort of numbers?
Thanks!
It is called "parity" addition or "XOR" (The word XOR originated from exclusive-OR). We still call it addition because this operation has many properties in common with standard decimal (or binary) addition: it is commutative and associative, and "adding" zero to a number doesn't change the number.
When adding two binary numbers by hand we keep the carry bits in mind and add it at the same time. But to do same thing in program we need a lot of checks. Recursive solution can be imagined as addition of carry and a^b (two inputs) until carry becomes 0.
Adding the numbers using the bitwise operators can also be done in a recursive manner. The same logic takes place but instead of a loop, we use a recursive function to do the Addition. In this code, a^b is the sum expression, and (a&b) << 1 is the carry expression after shifting.
Introduction. In computer programming, the use case of OR is that it is either a logical construct for boolean logic or a bitwise mathematical operation for manipulating data at the bit level.
as long as for two numbers num1 and num2 applies num1 & num2 == 0
, then follows:
num1 + num2 == num1 | num2
the reason for this is, that addition is basically a bitwise XOR, plus carry bit. But as long as there are no carry bits (num1 & num2 == 0
) then addition boils down to bitwise XOR, which is (again because of num1 & num2 == 0
) in this case logically equivalent to a bitwise OR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With