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.

5

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be a complete answer, you should summarize what it does.
@TedHopp As you wish... :)
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().

Comments

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.

Comments

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)

Comments

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.