2

I'm examining some SWT code and I'm having trouble understanding how the SWT constants work and particularly, how their bitwose OR works.

For example:

final Table leftTable = new Table(parent, SWT.MULTI | SWT.FULL_SELECTION);

I looked up SWT.MULTI in the API and found that its value is 1<<1. What does this mean? I did the same for SWT.FULL_SELECTION and found its value to be 13 (more understandable).

What does it mean to bitwise OR these? Is there a quick way to determine what the result is? Why is it done this way?

Baz
  • 36,440
  • 11
  • 68
  • 94
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • If you don't know what `1 << 1` means, I'd rather recommend to take a look at a Java tutorial. – Mot May 30 '13 at 08:22

1 Answers1

6

There is a complete list of the style bits here and an excellent explanation here and a general explanation on bitwise operators here.

<< is the left bit shift operator as explained here.


Let's make an example:

Assuming you have two style bits:

SWT.FOO = 4  // 100 binary
SWT.BAZ = 2  // 010 binary

If you now give SWT.FOO | SWT.BAZ to the Table, the result will be:

   100
OR 010
   ---
   110 // 6 in decimal

The table now wants to find out if you selected SWT.BAZ. It can do so by checking the following:

int styleBit = 6; // 110 binary

if((styleBit & SWT.BAZ) == SWT.BAZ)
{
    System.out.println("SWT.BAZ selected");
}

You can verify this calculation here.

Baz
  • 36,440
  • 11
  • 68
  • 94