Bitwise AND and you: how to store many flags as a single value

Hi there, sports fans! The new Jump into Javascript is on its way (along with the Trilobytes freebie plugin) but for now, I'm here with a tutorial on a little trick you may not be aware of: bitwise AND! (&)

First of all, for anyone not yet aware of this, computers don't really understand numbers the way we do. Base 10 is a foreign concept to them; they work in base 2, or binary. What we see as the integer 7, for example, would be 111 to a computer (or rather, something like 0000 0111 when dealing with full bytes, but that's a topic for another time). Where our number system has a 1s place (10 ^ 0), a 10s place (10 ^ 1), a 100s place (10 ^ 2) etc. with each place being the next power of 10 up (for example, the integer 409 means there are 4 100s, 0 10s and 9 1s) binary goes up in powers of 2: it has a 1s place (2 ^ 0), a 2s place (2 ^ 1), a 4s place (2 ^ 2), an 8s place (2 ^ 3), a 16s place (2 ^ 4) etc. So 111, 7, is really "one 4, one 2, one 1".

So how does this help us when storing flags? Simple! Since there are only two possible values for a binary digit, each one effectively acts as a switch. It's either 0 (off) or 1 (on). We can take advantage of this to stuff many switch values into one number.

Let's say you have 4 NPCs that have to be talked to, and then a 5th NPC that will offer a quest once you've spoken to those 4. Now you could use switches for that, but that's an allocation of 4 game switches just for one quest, which isn't great economy. Or you could use a variable that goes up by 1 every time you speak to an NPC, and that's great, but what if, when you haven't talked to them all, we want the 5th NPC to tell you *which ones* you still need to talk to? With a variable, we don't have that information. We could use self switches, sure, but that's not flashy and impressive like this is about to be.

So the first thing to do is to assign each NPC a value; that value being the next "place" up in the base 2 hierarchy. So our first NPC is 1, the second is 2, the third is 4, and the fourth is 8. This allows us to verify any combination of NPC interactions: if the value is 5, we know you've spoken to the first and third NPCs. If it's 10, we know you've spoken to the second and fourth. If it's 11, you spoke to the first, third and fourth...and so on.

And sure, we could use base 10 comparisons here. We could reduce the value by the one we're checking for, and check whether it's still > 0, and if so we know that NPC was spoken to. But there's a far easier way to do that: bitwise AND.

To put it in the simplest possible terms, a bitwise AND operation compares two binary digits, and returns the resulting value when the only bits that are ON (1) are the ones where they were on in both of the digits. For example:

4 & 10

0100 & 1010

This would give us 0, because there is no bit in either number that's also 1 in the other number. In 4, only the 4 bit is on. In 10, the 8 and 2 bits are on.

3 & 7

0011 & 0111

This would give us 0011, or 3, because the only common bits are the 2 and the 1.

So how does this help us to verify flags? Well, if we take our NPC interactions variable and do a bitwise AND operation with the value of the NPC we're checking for, we'll get back that value if the relevant bit is on. So let's say our variable is 10 and we want to check whether you've spoken to the second NPC:

10 & 2

1010 & 0010

Since 2 is the only common bit, we'd get back 0010, telling us that this NPC has indeed been interacted with.

Now with only four values, that doesn't look massively impressive, but let's say we want to track...20 NPCs. Think about the expenditure that would take in terms of switches. With flags, it's simple: our value is going to be anywhere from 0 to 524,288.

Let's say it's 32,330 (0111 1110 0100 1010). This tells us that we've interacted with NPC 2 (2), 4 (8), 7 (64), 10 (512), 11 (1024), 12 (2048), 13 (4096), 14 (8192), and 15 (16384). You can check any one specific NPC with a bitwise AND operation for the associated flag. So if you want to know if you've interacted with NPC 11, you'd do your interaction variable & 1024.

This technique is in fact used in the base engine, believe it or not: in tilesets. Bitwise and operations are used to determine passability as each aspect of a tile is assigned a binary digit. For example, "star passability" is 16.

So there you have it! Bitwise AND can be a very powerful tool in your arsenal if you know how to wield it. But really, as long as you can multiply a number by 2, it's not hard to do. Do you use bitwise AND in your own development? If so, what do you use it for?
This is one of those underrated threads that should be appreciated. Thank you @Trihan.
I still don't get it really, can you give an event page example
on how to do it exactly? as its a bit confusing and complicated for me.
I still don't get it really, can you give an event page example
on how to do it exactly? as its a bit confusing and complicated for me.
1710862644339.png


1710862657062.png


1710862668974.png


1710862680244.png
@ATT_Turan I didn't know "&" and |= is a thing to do in JS only &&.
I need to test this out, but uses more variables, so would it also be possible
to use 1 variable in an array?

$gameVariables.setValue(2) = [1, 2, 4, 8, 16]

at npc 1: $gameVariables.value(2)[0]
at npc 2: $gameVariables.value(2)[1]
at npc 3: $gameVariables.value(2)[2]
at npc 4: $gameVariables.value(2)[3]
at npc 5: $gameVariables.value(2)[4]
or is it than more complicated to make the checks?
@ATT_Turan I didn't know "&" and |= is a thing to do in JS only &&.
Trihan's first post showed & for bitwise AND, although he didn't include | to set the bit.

would it also be possible to use 1 variable in an array?
or is it than more complicated to make the checks?
That doesn't make any difference. Referencing one element in an array is the same as referencing one variable for all operators.
Code:
$gameVariables.value(2)[5] + 7
$gameVariables.value(3) + 7
$gameVariables.value(4)[9] + $gameVariables.value(2)[13]
all of these work the same. There's no syntactical difference between the bitwise operators and the arithmetic ones.
My example would actually only use one variable, and add 1/2/4/8 to that variable instead of setting a variable to be that value.
so towncheck 0

than townchck += 1 | +=2 | +4 etc?
than check the other othervarible to see which one you missed?

if so, it's a nice trick I didn't know, which makes more sense., its also a bit more clearer,
I need to make some more test to set this up, for 1 npc its working though 🙂
than townchck += 1 | +=2 | +4 etc?
No...that is not anything like the syntax I demonstrated above.

+ adds two values together. | will set the bit unless it already is.
What we see as the integer 7, for example, would be 101 to a computer (or rather, something like 0000 0101 when dealing with full bytes, but that's a topic for another time). Where our number system has a 1s place (10 ^ 0), a 10s place (10 ^ 1), a 100s place (10 ^ 2) etc. with each place being the next power of 10 up (for example, the integer 409 means there are 4 100s, 0 10s and 9 1s) binary goes up in powers of 2: it has a 1s place (2 ^ 0), a 2s place (2 ^ 1), a 4s place (2 ^ 2), an 8s place (2 ^ 3), a 16s place (2 ^ 4) etc. So 101, 7, is really "one 4, zero 2s, one 1".

I hate to be that person, but it looks like no-one else is stepping up, so.

7 is 111, not 101.
I hate to be that person, but it looks like no-one else is stepping up, so.

7 is 111, not 101.
You are correct. I either meant 111 or 5, will fix.
Do you use bitwise AND in your own development?
To be honest, I can't think of many realistic scenarios where I might be doing this in RPG Maker. If I really felt the need to try to pack multiple switches into one variable, I'd rather just turn that variable into an array or an object, and then I could store as many individual values in the variable as I wanted.

IMO, in most cases, the potential memory savings from instead using bit manipulation techniques would be very negligible on modern computers. Using arrays or objects to store individual values offers advantages in terms of readability, maintainability, and ease of implementation, and I wouldn't sacrifice that just to save a few bytes of RAM in an RPG Maker game.

But, for anyone who feels like they do want to use bits as flags, here are some functions that will allow you to manipulate them without having to do math:
JavaScript:
// Set a bit at 'pos' position in 'num' number
function setBit(num, pos) {
  return num | (1 << pos);
}

// Unset a bit at 'pos' position in 'num' number
function unsetBit(num, pos) {
  return num & ~(1 << pos);
}

// Toggle a bit at 'pos' position in 'num' number
function toggleBit(num, pos) {
  return num ^ (1 << pos);
}

// Get a bit at 'pos' position in 'num' number
function getBit(num, pos) {
  return (num >> pos) & 1;
}

Note that the first position is 0
more confusing stuff, but how does the scriptcall works this way?
I still figure out the rest with multiple one for checking.

I try to learn more as this is really interesting.
JavaScript:
// Set a bit at 'pos' position in 'num' number
function setBit(num, pos) {
return num | (1 << pos);
}

// Unset a bit at 'pos' position in 'num' number
function unsetBit(num, pos) {
return num & ~(1 << pos);
}

// Toggle a bit at 'pos' position in 'num' number
function toggleBit(num, pos) {
return num ^ (1 << pos);
}

// Get a bit at 'pos' position in 'num' number
function getBit(num, pos) {
return (num >> pos) & 1;
}
Note that the first position is 0
more confusing stuff, but how does the scriptcall works this way?
I still figure out the rest with multiple one for checking.

I try to learn more as this is really interesting.
Dunno if I can really explain it too well, but if you look at the number 0 in binary, it could be represented as:
0000

Imagine that as 4 switches that are all OFF. Say that we want to turn the first switch (starting from the right) to ON, it would be:
0001

If both the first and the second switch are ON, it would be:
0011

If the first and third switches are ON, and the fourth and second switch are OFF, it would be:
0101

And so on and so forth. You don't really have to care what the number represents in base 10--just focus on the binary form and imagine each digit as an individual switch. I'm only showing 4 digits, for the sake of simplicity, but you can actually have much more in one number.

The functions that I provided will allow you turn on/off the switches, and determine their values, without having to worry about converting numbers and such. So say that we want to turn ON the third switch, you'd use the setBit function that I provided:

Code:
let num = 0; // now num is 0000 in binary
num = setBit(num, 2); // now num is 0100

Since the first digit (from the right) is position 0, then that means that the third digit is position 2, hence why I used a 2 as the position argument in the setBit function.

To turn a switch OFF, you'd use the unsetBit function. And to check whether a switch is ON or OFF, you'd use the getBit function. Here are some examples:
JavaScript:
let num = 0; // now num is 0000 in binary
num = setBit(num, 2); // now num is 0100
num = setBit(num, 3); // now num is 1100
// It can have more than only 4 bits
num = setBit(num, 4); // now num is 11100
num = setBit(num, 5); // now num is 111100
num = setBit(num, 0); // now num is 111101

// You can check if a bit is set using an explicit comparison
if (getBit(num, 2) === 1) {
  console.log('The third bit is set');
}

// Or you can use the implicit comparison, since 1 is truthy and 0 is falsey
if (getBit(num, 2)) {
  console.log('The third bit is set');
}

num = unsetBit(num, 2); // now num is 111001

if (!getBit(num, 2)) {
  console.log('The third bit is not set');
}

// You can use game variables as well
$gameVariables.setValue(10, 0); // now variable 10 is 0000 in binary
$gameVariables.setValue(10, setBit($gameVariables.value(10), 5)); // now variable 10 is 100000
I save it, as example to make it more clear.

I believe << 0000 or more starting from the right while >> from the left?
not sure on the ~ or ~~ symbol but I look into this later what it does.

but your explanation on using your seems really simplified and more understandable.
thank you for the explanation, it makes things really clear for me.
I believe << 0000 or more starting from the right while >> from the left?
not sure on the ~ or ~~ symbol but I look into this later what it does.
Those are more bitwise operators. << shifts all bits to the left a specified number of times, >> shifts all bits to the right a specified number of times, and ~ flips all the bits (the 0s become 1s and the 1s become 0s). If you want to read more about them, here are some links: left shift, right shift, bitwise NOT.
I do get the >> and <<, but ~ and ~~ still confusing, not that I use it anyway.
thanks for the links.
For ~, you literally just change all 1 bits to 0 bits, and all 0 bits to 1 bits. Say you've got the binary 0000. If you ~ it, it will be become 1111. Say you've got 1010. If you ~ it, it will become 0101. Say you've got 1111. If you ~ it, it will become 0000. You just gotta flip the bits.

~~ isn't actually a thing, so I'm not sure where you saw that. All that would do is flip the bits twice, which means that you'd wind up with the exact same bits that you started with.

But honestly, I wouldn't worry about it too much. Generally speaking, you're not going to be using these bitwise operations in JavaScript. If you're having to mess with bits, then you're probably either doing some really low level stuff, or you're in a situation where performance and memory consumption is very critical. But in either of those situations, JavaScript is probably not the right language to be using.
I saw ~~ in some scripts, of a japanese plugin, no reason why,
even on the link it give a different output, so I cannot really pinpoint
what it does, if I find the plugin that has that function, I send it here.

I cannot recall which one, but it's a plugin Ovate shares from others
here, so I have to spit through them which one it was.

Edit: @Arthran here is a small snippet from a plugin that uses ~~ in the code
on ActorOrEnemy (entire plugin found [here] of BalloonInBattle.
you might understand it more, so not sure, he has some others using that too.
JavaScript:
    Window_Balloon.prototype.track = function (spriteBattler) {
        var actorOrEnemy = spriteBattler._battler ? (spriteBattler._battler.actor || spriteBattler._battler.enemy).apply(spriteBattler._battler) : null;
        this.x = spriteBattler.x - (this._width / 2) +
            (actorOrEnemy ? (~~actorOrEnemy.meta['SpeechBalloon/X']) : 0);
        this.y = spriteBattler.y - (spriteBattler.torigoya_getBattleHeight() + this._height) +
            (actorOrEnemy ? (~~actorOrEnemy.meta['SpeechBalloon/Y']) : 0);
    };
I see. Basically, JavaScript is a bit weird in that, if you use any bitwise operation on a value that is not an integer, it will first convert the value into an integer, and then it will perform the bitwise operation. As I mentioned before, using ~~ will simply flip the bits twice, which will wind up giving you the same number that you started with. However, since it's a bitwise operation, it will first convert the value into an integer, before it flips the bits twice.

In short, the author is using it as a shorthand way to convert the value into an integer number.

JavaScript:
let variable = "15.5"; // variable contains the string "15"
variable = ~~variable; // variable now contains the number 15

variable = 15.1337; // variable contains the number 15.1337
variable = ~~variable; // variable now contains the number 15

variable = 1337; // variable contains the number 1337
variable = ~~variable; // variable still contains the number 1337

I hadn't seen anyone do that before. Usually, I've seen people do it like this:
JavaScript:
let variable = "15.5"; // variable contains the string "15.5"
variable = variable | 0; // variable contains the number 15

Using | 0 probably has better performance than using ~~, since it only has to perform one operation (as opposed to two), but the difference should be pretty negligible either way. Pretty much any bitwise operation that doesn't actually change the resulting bits could be used to force the conversion, so it's up to your personal taste, but it would generally make your intentions more clear (to other people who might be reading your code) to use the conversion functions (i.e. parseInt) that JavaScript provides.

Original thread: https://forums.rpgmakerweb.com/threads/bitwise-and-and-you-how-to-store-many-flags-as-a-single-value.165338/