Bitwise comparison?

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Bitwise comparison?

1. Registered User
Join Date
Jul 2004
Posts
83

## Bitwise comparison?

How does bitwise comparison work?
if i had :
int i=0;
long j=3;
Integer k;
while(j>0)
{
i+=(int)j;
System.out.print(" "+i);
j = j >> 1;
}
k = new Integer(i);
System.out.println(" "+k.toBinaryString(i));

2. Banned Member
Join Date
Feb 2004
Posts
808
there is no comparison occurring here.. the operator >> and << are bit SHIFTERS

they move bits:

0010 0110 << 1 =
0100 1100

0000 0000 1111 0000 1010 << 7 =
0111 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:

1111 0000 &
1010 1100
1010 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)

else

if((perms & ARCHIVE) == ARCHIVE)
setArchive(file)
else
unsetArchive(file)
whats happening here?
perms = 6
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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise
 Questions? Contact us. C++ Web Development Wireless Latest Tips Open Source