in reply to Re: Modifying multiple bits in a byte - bitwise operators
in thread Modifying multiple bits in a byte - bitwise operators
Yes, the generic set of HLL operations to set a field of bits is to do a bit-wise AND with a one's complement of a "mask" to make sure the bits are all unset, then do a bit-wise OR operation to set those bits to however you want them.
The difference between the HLL version and an actual Assembly language implementation is that there is some uncertainty in how big a "natural integer" is with the HLL. With assembly, I know exactly whether I've got 8, 16, 32, or 64 bits. Typically with HLL, you only know something like size >= 32 bits for an int.
So, with ASM, the "negate the MASK" step would not be there. The ~MASK value would have been compiled in as a "load immediate" constant. With HLL, we want to actually calculate this "flipping of bits" mask. When we calculate ~0x3, we get 2 bits of zeroes and as as many leading one bits as needed to make up the "native int". Design for a min size int, but allow bigger ints.
Here is some code with a couple of things I like to do:
use strict; use warnings; use constant {UP => 0x0<<3, DOWN => 0x1<<3, LEFT => 0x3<<3, RIGHT => 0x2<<3, MASK => 0x3<<3}; printf "direction Mask: "; print8bits (MASK); #Prints: direction Mask: 0001 1000 my $register8b=0; #set direction left $register8b = $register8b & ~MASK | LEFT; print8bits ($register8b); #Prints: 0001 1000 #set direction down $register8b = $register8b & ~MASK | DOWN; print8bits ($register8b); #Prints: 0000 1000 sub print8bits { my $int = shift; print map{s/(\d{4})/$1 /g;$_;}sprintf "%08b\n", $int; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Modifying multiple bits in a byte - bitwise operators
by stevieb (Canon) on Jan 11, 2017 at 14:11 UTC |