I'm a bit confused after reading about how to use bitmasks to store boolean values. I would like to have a set of boolean values and then generate a unique integer for each combination of the values. Here is the current system so far:
var a = 1 << 1
var b = 1 << 2
var c = 1 << 3
var d = 1 << 4
var uniqueint1 = getInt(true, false, false)
var uniqueint2 = getInt(true, true, false)
var uniqueint3 = getInt(true, true, true)
// ...
function getInt(x, y, z) {
var value = a
if (x) value = value | b
if (y) value = value | c
if (z) value = value | d
return value
}
But the problem is, I am not sure if I am supposed to handle the "not" case, along the lines of this:
function getInt(x, y, z) {
var value = a
if (x) value = value | b
else value = value ^ b
if (y) value = value | c
else value = value ^ c
if (z) value = value | d
else value = value ^ z
return value
}
All I know is that I've seen |
, &
, and ^
related to bitmasks, and I know to find if a boolean is in the bitmask you do var yes = value & b
, but I'm just confused how to generate the bitmask so that it handles both the if (true) and if (false) cases. Not sure if I'm supposed to be using ^
somewhere, or what else I'm doing wrong. Please advise. Thank you!
I am not sure if I am supposed to handle the "not" case
You're not supposed to handle it at all. A bitmask works so that you either have a bit with value 1
if your flag is set or the bit with value 0
if not. Given that your value starts with 0
s everywhere (the integer 0), you just have to set the bit (by OR 1) when your condition is true and you don't have to do anything otherwise.
You could simplify your code to
function getInt(x, y, z) {
return (0b10 // a
| (x << 2) // 0b00100 if x and 0b00000 else
| (y << 3) // 0b01000 if y and 0b00000 else
| (z << 4)); // 0b10000 if z and 0b00000 else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With