More often than as a bit number, these binary bits are defined in a "bit mask".
It is important to understand the difference between just & (bit wise and) and && (high priority logical and).
Also important is the difference between ~ (bit inverse) and ! (logical not).
Complex binary manipulation can be difficult in the High Level Language (Perl or even C) because you don't know how many bits you are dealing with (16,32,64).
However, these simple idioms suffice for most common cases.
Some example code:
Update: I suppose that something like: use constant allBits => upload | getTicket | downLoading | whatEver | moreEver; is possible in favor of ~0 (which means turn all bits in the integer register ON). Often you don't want to cause any bits to be turned on which are not specified.use strict; use warnings; use constant { upload => 1, # same as 0b1 getTicket => 2, # same as 0b10 downLoading => 4, # same as 0b100 whatEver => 8, # same as 0b1000 moreEver => 16,# same as 0b10000 }; my $stats = upload | getTicket | downLoading | whatEver | moreEver; print "numeric representation in decimal of all bit set is: $stats\n\n +"; # check if getTicket is on? print "checking if getTicket is on?\n"; $stats & getTicket ? print "getTicket is ON\n\n" : print "getTicket is + OFF\n\n"; # turn getTicket off print "turning getTicket off...\n"; # note: we need bitwise "and, which is &" and ~ instead of logical ! $stats = $stats & ~getTicket; # ~ means bit inverse of bits print "numeric decimal value = $stats\n"; # check if getTicket is off? print "check if getTicket turned off?\n"; $stats & getTicket ? print "getTicket is ON\n\n" : print "getTicket is + OFF\n\n"; # flip status of just getTicket print "flipping state of getTicket...\n"; $stats = $stats ^ getTicket; print "numeric decimal value = $stats\n"; $stats & getTicket ? print "getTicket is ON\n\n" : print "getTicket is + OFF\n\n"; print "flipping state of getTicket...\n"; $stats = $stats ^ getTicket; print "numeric decimal value = $stats\n"; $stats & getTicket ? print "getTicket is ON\n\n" : print "getTicket is + OFF\n\n"; __END__ numeric representation in decimal of all bit set is: 31 checking if getTicket is on? getTicket is ON turning getTicket off... numeric decimal value = 29 check if getTicket turned off? getTicket is OFF flipping state of getTicket... numeric decimal value = 31 getTicket is ON flipping state of getTicket... numeric decimal value = 29 getTicket is OFF
In reply to Re: How can I set a bit to 0 ?
by Marshall
in thread How can I set a bit to 0 ?
by bartender1382
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |