counting matching bits / bitXnor
Paolo Bonzini
bonzini at gnu.org
Mon Dec 17 17:25:41 UTC 2007
Cees de Groot wrote:
> I *understand* it, but it's not what I *want* :).
The point is that, there is no reason why 0 bitInvert should return 1
rather than 3, 7, or 15.
Your data type is a BitArray, but if you encode it as an Integer, that's
not enough. You need another instance variable to store the width or
alternatively a mask (i.e. (1 bitShift: width) - 1). Then, you have
something like this:
(the bitOr:'s in the masks are not typos).
& aBitString
^BitString
value: (self value bitAnd: aBitString value)
mask: (self mask bitOr: aBitString mask)
| aBitString
^BitString
value: (self value bitOr: aBitString value)
mask: (self mask bitOr: aBitString mask)
invert
^BitString
value: (self value bitXor: self mask)
mask: self mask
xor: aBitString
^BitString
value: (self value bitXor: aBitString value)
mask: (self mask bitOr: aBitString mask)
xnor: aBitString
^(self xor: aBitString) invert
count
| n cnt |
n := self value. cnt := 0.
[ n = 0 ] whileFalse: [
cnt := cnt + 1.
n := n bitAnd: n - 1 ].
^cnt
Paolo
More information about the Squeak-dev
mailing list
|