0

So I was reading the example source code from this Android page on ViewGroups, and I came across these lines:

// Report our final dimensions.
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
        resolveSizeAndState(maxHeight, heightMeasureSpec,
                childState << MEASURED_HEIGHT_STATE_SHIFT));

So I hope to learn:

  1. What does the << operator exactly do in Java?

  2. What is happening in last line of the aforementioned snippet?

Thanks.

Behnam
  • 6,510
  • 6
  • 35
  • 65

5 Answers5

4

It isn't an operand, it is an operator. A bit-wise shift operator, to be exact.

Given x and y as operands, x << y shifts the bits of the x value y bits to the left. It is basically the same as multiplying by 2 to the power y.

Dave
  • 4,282
  • 2
  • 19
  • 24
2

<< is one of bit shifting operator.

It is quite offen we use higher 16 bits of one single 32 bits int for one thing and lower 16 bits of another thing.

childState << MEASURED_HEIGHT_STATE_SHIFT means childState is passing a height (in its lower 16 bits) which is expecting to be in higher 16 bits of the int passing to resolveSizeAndState().

pinxue
  • 1,736
  • 12
  • 17
1

This is Bitwise and Bit Shift Operators. More info can be found at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

For Ex:

1111 1110 << 2 
1111 1000  // Have added 0 from right

0001 1111 >> 3 
0000 0011 // Will preserve MSB and shift it right

If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C afaik, and maybe more) a triple-sign-operator:

1100 1100 >>> 1
0110 0110 
An SO User
  • 24,612
  • 35
  • 133
  • 221
AndroidHacker
  • 3,596
  • 1
  • 25
  • 45
1

"<<" is a bit operator.

I quote the explaination from tutorial for Java

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right.

And also I quote an example from here

int a = 60;     /* 60 = 0011 1100 */
int c = 0;
c = a << 2;     /* 240 = 1111 0000 */

so you can see a << n is almost a*(2^n)

Merlin
  • 125
  • 7
1
  1. What does the << operator exactly do in Java? It's moving bits to the left. As mentioned in previous answers:

    1111 1110 << 2 1111 1000 // Have added 0 from right

What is happening in last line of the aforementioned snippet? Code is changing state. It's sometimes used to represent states. e.g.

state1 = 1 << 0;
state2 = 1 << 1; 
state3 = 1 << 2;

so you have 3 unique states.

Martin Vandzura
  • 3,047
  • 1
  • 31
  • 63