Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent 4 boolean possibilities in a single value

I want to store 4 boolean possibilities in a single value. For example, I want a single value that tells whether a person is:

IsSingle
IsGraduate
IsMale
IsLookingForPartner

So is it good to store them in a byte, whose 4 bits may be allocated, one for each parameter. If the bit is set to 1 then that boolean parameter is true. So I can do bit shift operations to find what all are true. if value of byte is 111 then first three parameters are true. Is it a good way? Is there a better way to implement this?

I need to store this value as a single parameter in the database.

like image 280
Rajat Gupta Avatar asked Mar 12 '11 13:03

Rajat Gupta


1 Answers

Bit flags.

public static final int IsSingle = 1 << 0;
public static final int IsGraduate = 1 << 1;
public static final int IsMale = 1 << 2;
public static final int IsLookingForPartner = 1 << 3;

...

if ((Value & IsSingle) != 0) {
}

if ((Value & IsGraduate) != 0) {
}

// Set "Single"
Value |= IsSingle;

// Remove "Graduate"
Value &= ~IsGraduate;
like image 108
Erik Avatar answered Sep 27 '22 21:09

Erik