0

suppose I write some very simple tests in an android app working on simulator (marshmallow, OSX 64 bits) whith logcat output:

Log.i("test","long int = "+17301768L);
Log.i("test","long int = "+(1<<3 | 1<<8 | 1<<19  | 1<<24));
Log.i("test","long int = "+ 8607236360L);
Log.i("test","long int = "+(1<<3 | 1<<8 | 1<<19  | 1<<24  | 1<<33));

…logcat prints:

long int = 17301768
long int = 17301768
long int = 8607236360
long int = 17301770

Obviously, last line is not correct : it should be the same as the third line.

Why ? And how can I make it working as expected ?

Chrysotribax
  • 789
  • 1
  • 9
  • 17

1 Answers1

3

By default all numbers in Java are of type int. Therefore the numbers you create using the binary operations are int values, too:

(1<<3 | 1<<8 | 1<<19  | 1<<24  | 1<<33)

1<<33 = 2
1L<<33 = 8589934592

int values are limited to 31 bits + 1 bit for indicating positive/negative value. Therefore setting the 34th bit does not change anything.

To make it work you have to explicitly use long values for all bits that does not fit into an int. You can do that by adding "L" for long to the number.

    System.out.println((1<<3 | 1<<8 | 1<<19 | 1<<24 | 1L <<33)); // 8607236360
Robert
  • 39,162
  • 17
  • 99
  • 152