Save bool variables as int and read them back

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mnejc

I have multiple bool varables:
var 0=1
var 1=0
var 2=0
var 3=1

I can save them as
var (int) decimal = 9

How can I find value for var 1 from decimal variable?

:bust_in_silhouette: Reply From: alireza49

You can use bitwise operators. In this case use AND (&) operator. For instance decimal & 0x01 returns a value related to 1st bit , decimal & 0x02 returns a value related to 2nd, decimal & 0x04 returns a value related to 3rd bit and so on. If the returned value is 0 it means that the corresponding bit value is 0, and if the returned value is not 0 then the corresponding bit value is 1

:bust_in_silhouette: Reply From: jgodfrey

I think you’re looking for something like this:

func _ready():
	print(is_bit_set(9, 1))
	print(is_bit_set(9, 2))
	print(is_bit_set(9, 3))
	print(is_bit_set(9, 4))

func is_bit_set(value, bit):
	return (value & (1 << (bit - 1))) > 0

Output:

True
False
False
True