Using integers to store multiple Boolean values

Shubham Agrawal
2 min readMar 16, 2020

Problem:

We all know that a Boolean variable generally takes one byte of memory in programming. And do you think we need a complete byte to just represent true or false??? According to me, one bit is enough(as you just need 0 or 1) then why to have extra 7 bits?

Solution:

Use integers to store multiple Boolean values. As integers are generally of 32 or 64 bit. So we use one bit of integer as one Boolean value than we can use it for 32 Boolean variables and can save us to approx 24 bytes which is huge.

For eg:

Suppose we want to know the color(VIBGYOR) used in a image.
One way is your API returns 7 different Boolean variable
1) isVioletUsed
2) isIndigoUsed
3) isBlueUsed
4) isGreenUsed
5) isYellowUsed
6) isOrangeUsed
7) isRedUsed

Another way is to use one integer and represent all 7 values by bits:
Violet = 1, Indigo = 2, Blue = 4, Green = 8, Yellow = 16, Orange = 32, Red = 64
Now suppose we want to send 3 colors red, blue and green, so we can only set those bits
color = Red | Blue | Green = 64 | 4 | 8 = 76 (0b1001100),
but in Boolean variable design you would require to send all the variables.

So this way we can save size and number of variables, if you think this in term of database tables, so one integer is equivalent to 32 Boolean column(too many column is also a pain).

Readability wise obviously first approach is better so this is a trade-off between readability and space.

Setting a bit

number = number | a

Setting multiple bits

number = number | a | b | c

To unset a bit

number = number & (~a)

To unset multiple bits

number = number & (~(a|b|c))

To check a bit is set or not

(number & a) > 0
or
(number & a) == a

To check multiple bits are set or not

number & ( a | b | c) == (a | b | c)

To check a is set and b is not set

number & (a | b) == a

To check a is set and b is not set and c is set

number & (a | b | c) == (a | c)

Note: here a, b, c are power of 2(1, 2, 4, 8, 16…) not bit number.

--

--