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.
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;
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