I am building a lightweight high-precision arithmetic library for one of my Java applications and have been doing quite a bit of bit-twiddling (pun intended). Occasionally I get an int that has to be be converted into a long via simple word extension i.e. the 32 least significant bits of the long should become equal to the bits of the int.
Unfortunately, casting only works correctly for positive numbers. In addition, using an int in the same arithmetic expression with a long will implicitly cast to long beforehand, which means that e.g. this will not work if i is negative:
long l = (i & 0xffffffffL);
Currently I am using something along the lines of:
long l = (((long)(i >>> 8)) << 8) | (i & 0xff);
Is there a more elegant way to do this?
EDIT:
I may be missing something:
int i = -1;
long l = (i | 0xffffffffL);
System.out.println(l);
This prints out -1 rather than 4294967295. What am I missing?
EDIT 2:
Ooops… | instead of &. How the **** did the little ****** get there?
EDIT 3:
I have no idea how exactly I missed it, but this works perfectly:
long l = (i & 0xffffffffL);
…which makes this question completely irrelevant, I guess.
Did you actually test the
long l = (i & 0xffffffffL);code? Yes, the value ofiwill be converted to long first, which means either 0-extension ifiis positive or 1-extension ifiis negative. In either case the lower 32 bits are not affected, so unless I misunderstand the problem, the&operation should leave you with the result you want.