I'm not too savvy on the whole binary ... but I'm learning. I'm beginning to learn about logical bitwise operators like AND operators, OR operators, etc. I know that these are used for boolean expressions with two operands (&, |, &&, ||, etc.), however I'd love to know how, in terms of binary, they actually work. For example, this explanation of the AND operator (here) goes right over my head because of my still limited knowledge of binary.
I know what these operators do, I just want to know how they work! :) So basically, could someone please explain how bitwise operators like OR, AND, XOR, etc. work?
Also, however, I would love if someone could give me an explanation of bitwise shift operators. And also a context in which it would actually ever be used, if ever. :)
Thanks very much,
asked Apr 22 '12 at 02:36 PM
In assembly programming :
See the first four bits (MSB) are cleared while the last four remains the same, you need 1 AND 1 to get 1
The four last bit (LSB) are set to 1 because you need only one 1 to get 1... 1 OR 0 =>1
XOR is the most confusing
It is one or the other gives 1 but if both then 0.
The big idea being that at processor level, a lot of computation are based on flags, meaning that the processor checks a particular bit inside a byte to define the state.
Consider a byte of a router for communication, 00000001 could represent the system is on. 00000011 the system is on and sending information, 10000000 the system is down and so on. You would use AND OR XOR to define the state of the device.
For shift operator I think you meant, when a byte is shift to the right or the left. That is used for example in multiplication and division by two.
Well, I could write up a big paragraph here. But, it has already been done:
Essentially, the computer represents a number with a sequence of bits and bitwise operators manipulate individual bits rather than the entire number to change the number in controlled ways.
Bitwise shift operators are quick ways to multiple numbers by powers of 2 (among other things). Bit operations are also used to compare numbers containing a number of "flag" values with just the flag value of interest.
A bit string can be an efficient way to represent a lot of bools in a row. Unity uses it mostly for layerMasks. Instead of setting:
You can store up to 32 layer yes/no's in a single int. Even better, the computer's built in hardware can check if the layers match in only 1 step (binary and's, or's ... are built into the chip) instead of using 32 if's.
In the old days, you used it everywhere, to save space. Sometimes, if you have two values that never went past 0-15, you used bit-shifting to have them share one 8-bit word. It took longer to read them, but back then 32K was a big computer, so every byte counted.
answered Apr 22 '12 at 04:52 PM