in reply to Modifying multiple bits in a byte - bitwise operators
#!/usr/bin/perl use warnings; use strict; my $mask1 = 0b1101_1101; my $mask2 = 0b0010_0010; printf " \$mask1 = %b\n", $mask1; #Use bitwise NOT to flip all the bits. printf "~\$mask1 = %b\n\n", ~$mask1; #use bitwise OR to set bit(s) but keep original values for all other b +its. my $value = 0b1010_1000; printf " %b \$value\n| %b \$mask1\n----------\n %b\n\n\n", $value, $ +mask1, $value | $mask1; printf " %b \$value\n| %08b \$mask2\n----------\n %b\n\n\n", $value, + $mask2, $value | $mask2; #use bitwise AND to clear bit(s) but keep original values for all othe +r bits. printf " %b \$value\n& %b \$mask1\n----------\n %b\n\n\n", $value, $ +mask1, $value & $mask1; printf " %b \$value\n& %08b \$mask2\n----------\n %08b\n", $value, $ +mask2, $value & $mask2; #If you just want to test the value of a bit then clearing the other b +its # lets you test the value for the remaining one. __END__ $mask1 = 11011101 ~$mask1 = 111111111111111111111111111111111111111111111111111111110010 +0010 10101000 $value | 11011101 $mask1 ---------- 11111101 10101000 $value | 00100010 $mask2 ---------- 10101010 10101000 $value & 11011101 $mask1 ---------- 10001000 10101000 $value & 00100010 $mask2 ---------- 00100000
|
|---|