Quote (umeshieee @ Jun 20 2016 06:56pm)
Bitwise ANDs/ORs are used in performing operations on bits like 0011 AND 1010. These operators are mainly used for lower level programming languages and not languages like java (generally).
I wouldn't say that. You can use bitwise manipulations in any language for a multitude of things. Such as truth tables and networking protocols. Hell if you ever have to write your own serializer you may want to use them.
In the networking example say you needed to add the length of the packet to the first 2 bytes of the message. You simply can't insert the decimal (when working with raw bytes) so you would have to use bit shifts and bitwise ands to insert the value into the two bytes. Well I guess you could avoid them if you use a higher level engine which automatically does these things for you, but there is no reason not to learn it as they are not difficult.
Code
packet[0] = (0xff00 & (length)) >> 8;
packet[1] = (0xff & (length));
Let's add some values to this. Let Length be 1500 (0x05DC). The first operation does a bitwise and against 0xFF00. When we view this at the binary level we can see whats happening
Code
(FF00) 1111 1111 0000 0000
(05DC) 0000 0101 1101 1100
-----------------------------------
(0500) 0000 0101 0000 0000
If we recall "and" means "if both bits/operands are true (1) then the result is (1), else the result is 0". From this we can tell that by using the magic number we did, we could specify which bits we wanted to keep and discard the rest. The magic number is usually 0's and F's because they represent all 1's or all 0's in binary. In this case we kept the first 8 bits which which returned 0000 0101 0000 0000, skipping the first four, 1&0 = 0, 1&1 = 1, 1&0=1, 1&1=1 following the rules of the bitwise and.
Next we shift our number 8 bits to the right so our value we extracted from our original length is 0x05. The process is repeated to extract the bottom half of our length to fill our other byte in our packet.
More on magic numbers:
Say we wanted to extract the last half byte of data from 0x05DC, we could specify 0x000F as our magic number. In turn this equates to:
Code
(FF00) 0000 0000 0000 1111
(05DC) 0000 0101 1101 1100
-----------------------------------
(000C) 0000 0000 0000 1100
------------------------------------------------------------------------------------
Trueth tables using flags are great as well if you have a bunch of tasks that are required to be based off one another, but can't fit into clean if/ if else/ else logic.
http://smyck.net/2015/12/10/truth_tables/ this article explains truth tables quite well.
------------------------------------------------------------------------------------
For ferf, I suggest taking a read of this
http://pastebin.com/eqsL0v8g . It's an old paper, but it walks you through decimal, binary, and the bitwise operations.
This post was edited by AbDuCt on Jun 20 2016 07:46pm