Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are 'addition' and 'bitwise or' the same in this case?

Tags:

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 FFs.

Am I right in saying that addition and bitwise or would always produce the same output for such sort of numbers?

Thanks!

like image 783
Albus Dumbledore Avatar asked Sep 07 '11 13:09

Albus Dumbledore


People also ask

Is XOR same as addition?

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.

What is addition in bitwise?

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.

How do you use bitwise operators for addition?

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.

Is bitwise or and logical or same?

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.


1 Answers

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

like image 161
Andreas Grapentin Avatar answered Nov 29 '22 09:11

Andreas Grapentin