user1796942
user1796942

Reputation: 3528

Equivalent of C++ shift operator << in Java?

C++ shift operator << does not cycle. For example if you do:

// C++
int a = 1;
cout << (a<<38);

You get 0. But, in Java you actually cycle and get a valid value of 64.

I need to translate some C++ code to Java, so what do I use as the equivalent for <<?

Upvotes: 11

Views: 1391

Answers (2)

shuangwhywhy
shuangwhywhy

Reputation: 5625

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Please refer to Java Language Specification: http://docs.oracle.com/javase/specs/jls/se7/jls7-diffs.pdf

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47729

The Java language spec states:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f (0b111111). The shift distance actually used is therefore always in the range 0 to 63, inclusive.

So, in your example case, (int)(((long)a)<<38) should work.

Upvotes: 9

Related Questions