3 ms·
> I have read that book, and while it is a great read, it rarely employs realistic code you would run into (will you really cast some number literal multiple ti
by marginalia_nu 4y ago
> I have read that book, and while it is a great read, it rarely employs realistic code you would run into (will you really cast some number literal multiple times and try to guess the resulting value in actual prod code? And things like that)
There is some admittedly unintuitive behavior when it comes to type conversions, especially in bitwise operations. Like this is just nasty:
long f(int a, byte b) {
long ret = 0;
ret |= b;
ret |= (long) a << 8;
return ret;
}
System.out.println(Long.toHexString(f(100, (byte) 64))); // 0x6440
System.out.println(Long.toHexString(f(100, (byte) 129))); // 0xffffffffffffff81
// you need to do
long f(int a, byte b) {
long ret = 0;
ret |= Byte.toUnsignedLong(b);
ret |= Integer.toUnsignedLong(a) << 8;
return ret;
}
- 0xmarcin 4y agoThe problem is that in Java byte is _signed_ type. So `(byte) 129` is the actual source of the problem, the number is simply out of range (-128 to 127). Since there is no byte literal and numbers by default are integers you always have to cast when calling a function with byte parameter. There is simply no distinction between safe and unsafe cast...