Posts Tagged ‘bit arithmetic’

How to use flags in Java?

April 13, 2010

I learned to like flags in C/C++ because a single long number can hold 32 boolean values in one variable – in Java even more. This very often allows avoiding multiple collections of variables or containers storing such variables. So I liked to do the same in Java.

This is a short summary about how it works in Java.

1. This is just a small example how it works to set flags in Java:

public class MyClass {
// Set debug log level:
private boolean DEBUG = false; // is set via constructor
private final long DEBUGtoNULL = 0x00; // no file
private final long DEBUGtoSTDOUT = 0x01; // STDOUT
private final long DEBUGtoLOGFILE = 0x02; // LOG
// which log files to write to?
private long DEBUGlevel = DEBUGtoNULL;
//private long DEBUGlevel = DEBUGtoLOGFILE;
//private long DEBUGlevel = DEBUGtoSTDOUT;
//private long DEBUGlevel = DEBUGtoLOGFILE | DEBUGtoSTDOUT;

MyClass()
{
if(DEBUGlevel != DEBUGtoNULL) DEBUG = true;
else DEBUG = false;
}

// only log if any debug output media is selected
private void logIncludingTimeStamp(String line) {
if(!DEBUG) return;

// If STDOUT debug is requested
if( (DEBUGlevel & DEBUGtoSTDOUT) != 0) System.out.println(timeStamp + line);
// If LOG debug is requested
if( (DEBUGlevel & DEBUGtoLOGFILE) != 0) log(timeStamp + line);
}

2. Why to always use flags in HEX notation?

Because it is the easiest way to set them without remembering strange decimal numbers. For the HEX notation 1,2,4,8 and 0 are moving and filled up by 0 if the bits become higher. This makes it very easy to read as well. Octal numbers would also be an option but than the resulting numbers are longer.

BIT1 = 0x0001 // decimal 1 — octal 1
BIT2 = 0x0002 // decimal 2 — octal 2
BIT3 = 0x0004 // decimal 4 — octal 4
BIT4 = 0x0008 // decimal 8 — octal 10
BIT5 = 0x0010 // decimal 16 — octal 20
BIT6 = 0x0020 // decimal 32 — octal 40
BIT7 = 0x0040 // decimal 64 — octal 100
BIT8 = 0x0080 // decimal 128 — octal 200
BIT9 = 0x0100 // decimal 256 — octal 400
BIT10 = 0x0200 // decimal 512 — octal 1000
BIT11 = 0x0400 // decimal 1024 — octal 2000
BIT12 = 0x0800 // decimal 2048 — octal 4000
BIT13 = 0x1000 // decimal 4096 — octal 10000
BIT14 = 0x2000 // decimal 8192 — octal 20000
BIT15 = 0x4000 // decimal 16384 — octal 40000
BIT16 = 0x8000 // decimal 32768 — octal 100000

2. How to set multiple bits?

long MYBITCONTAINER = 0x0 // cleans all bits
long MYBITCONTAINER = BIT11 // sets bit 11
long MYBITCONTAINER |= BIT6 | BIT14 // now bit 6, 11 and 14 are set

3. How to check whether a bit is set?

if( (MYBITCONTAINER & BIT6) != 0) { System.out.println(“BIT6 was set!”); }
else { System.out.println(“BIT6 was not set!”); }