Jump to content

<< operator??

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
stack

stack

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
hi,
what does the mean of << operator in java
example:
  static boolean won[] = new boolean[1 << 9];
  static final int DONE = (1 << 9) - 1;

  static void isWon(int pos) {
	for (int i = 0 ; i < DONE ; i++) {
	    if ((i & pos) == pos) {
		won[i] = true;
	    }
	}
    }



  static {
	isWon((1 << 0) | (1 << 1) | (1 << 2));
	isWon((1 << 3) | (1 << 4) | (1 << 5));
	isWon((1 << 6) | (1 << 7) | (1 << 8));
	isWon((1 << 0) | (1 << 3) | (1 << 6));
	isWon((1 << 1) | (1 << 4) | (1 << 7));
	isWon((1 << 2) | (1 << 5) | (1 << 8));
	isWon((1 << 0) | (1 << 4) | (1 << 8));
	isWon((1 << 2) | (1 << 4) | (1 << 6));
    }
?

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
It's a bitwise-operator, used to manipulate bits.
"<<" is used to move each of the bits one place to the left.
<< 01001011
 = 10010110


#3
stack

stack

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
i dont understand the meaning of <<operator and | operator
please explain this code???

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
static boolean won[] = new boolean[1 << 9];
It makes an array of 512 booleans.
That's because:
<< 0000000000000001
 = 0000001000000000
And 0000001000000000 is binaries equivelant of decimals 512.

static final int DONE = (1 << 9) - 1;
It initializes DONE with a value of 511.
Look above. Afterwards, you simply subtracts one from the result.

if ((i & pos) == pos) {
Let's suppose i is 11 and pos is 12. Then the first calculation will give 8, and that's not equivelant to pos.
That's because:
  1011 [11]
& 1100 [12]
= 1000 [08]

...
isWon((1 << 3) | (1 << 4) | (1 << 5));
...
This will pass 56 to the function, isWon.
That's because:
<< 00000001
 = 00001000

<< 00000001
 = 00010000

<< 00000001
 = 00100000

------------

   00001000
 | 00010000
 | 00100000
 = 00111000


It looks like the coder only made the code in that way, to confuse the reader. It's a stupid way to code, and it's only annoying to look at. Sometimes it's good to do bit manipulation, but I see no reasons to do it in your example.

#5
evanator2005

evanator2005

    Newbie

  • Members
  • Pip
  • 2 posts
aaaaaaaaaahhhhhhhhhhhhhhh!

#6
Frantic

Frantic

    Learning Programmer

  • Members
  • PipPipPip
  • 91 posts
Like everyone else said, shift the bits left.

evanator2005 said:

aaaaaaaaaahhhhhhhhhhhhhhh!

What does this mean?