Re: bitwise operations limited to 32 bits
- Posted by DerekParnell (admin) May 04, 2010
- 1367 views
... but the same is not true for or_bits, xor_bits, and not_bits.
Why?
Because code such as
function setBit(atom mask, integer bit) return or_bits(mask,power(2,bit-1)) end function atom mask mask = setBit(0,35)
will now fail silently, leaving mask 0.
Of course the literal 35 makes this a bit blatent, but what if it is an enum, so your code works fine until you insert a few more flags?
As I said, there is a strong case for and_bits(<anything>,#FFFFFFFF) to return the perfectly valid answer, but are there any real-world or_bits etc examples that I am missing whereby it should quietly and incorrectly set the top bits of the input to 0s?
As documented, these bitwise functions only deal with sets of 32-bits, so therefore there are no 'top' bits outside those 32 bits. Also as documented, these functions only work on the lower 32-bits of any value presented to them; other bits are ignored. This is a very useful property when bit-twiddling for hashing and encryption. If one is play with bits for other purposes, those algorithms using the bitwise functions must also be intimately aware of what is happening to values under their care. So I would maintain that the example function you present ought to be rewritten more like ...
function setBit(atom mask, integer bit) if bit < 1 or bit > 32 then crash("'bit' parameter value %d is out of range", bit) end if return or_bits(mask,power(2,bit-1)) end function atom mask mask = setBit(0,35)
results in a crash and the message
'bit' parameter value 35 is out of range
The coder must take some responsibility at some point. The language cannot be expected to be the nanny.
Another approach might be to have a with option that suppresses certain runtime checks such as large values in bitwise functions. For example ...
without bit_errors -- No crashes with large values. --with bit_errors -- Crashes with large values (the default). function setBit(atom mask, integer bit) return or_bits(mask,power(2,bit-1)) end function atom mask mask = setBit(0,35)