there is no comparison occurring here.. the operator >> and << are bit SHIFTERS
they move bits:
0
010 0110 << 1 =
0100 1100
0000 0000
1111 0000 1010 << 7 =
0
111 1000 0101 0000 0000
see?
so << 1 is like multiply by 2
<< 2 like multiply by 4
so << N like multiply by 2^N
same for >> N but its divide by 2^N
---
bitwise comparison is done with & and | (not && and ||)
data is examined in columns, like a sum:
11
11 0000 &
10
10 1100
10
10 0000
the top bold 1 AND the bold 1 underneath it.. thats 1 AND 1 = 1 (italic 1)
then we have 1 and 0 = 0
then bold 1 and bold 1 = italic 1 (again)
then 1 and 0 = 0
(next group of 4)
0 and 1 = 0
0 and 1 = 0
0 and 0 = 0
0 and 0 = 0
for OR:
1101 0110 |
1001 1011 =
1101 1111
OR puts a 1 in the result wherever 1 or the other or both are a 1
what we use it for..is more complicated.. heres an example using AND ,and talking about file permissions
final int READONLY = 1
final int ARCHIVE = 2
final int SYSTEM = 4
final int HIDDEN = 8
so if a user calls: setPermissions("c:\temp", 6)
well that 6 =4+2 so archive and system are set, readonly and hidden are cleared, but how to put that in computer speak?
well:
6 = 0110 in binary
so:
Code:
public void setPermissions(String filename, int perms)
if((perms & READONLY) == READONLY)
setReadOnly(filename)
else
unsetReadOnly(filename)
if((perms & ARCHIVE) == ARCHIVE)
setArchive(file)
else
unsetArchive(file)
whats happening here?
perms & READONLY
perms = 6
readonly = 1
6 = 0110
1 = 0001
so bitwise compare:
0110 &
0001 =
0000
result is 0. result is != READONLY, so we unset read only
ARCHIVE = 2 = 0010
perms = 6 = 0110
0110 &
0010 =
0010
so result is = ARCHIVE.. so this is true and the action WILL be done
same result for SYSTEM
but perms & HIDDEN will == 0
so file will not be hidden
and thats how it can decode a number.. flags, bitflags we call em
