27 February, 2010

binary numeric promotion in java numeric types

I've been working on a Java backend for stupid, a crypto algorithm language proposed by Ben Laurie.

This has led me to look at Java numeric types a little more closely (and with a decade more cynicism than last time).

I'd forgotten entirely that there were short and long numeric types - for pretty much any use I've made of numbers in Java ever, int has been fine.

short behaves a little surprisingly:

If a and b are both long, then a & b is a long.

If a and b are both int, then a & b is an int.

If a and b are both short, then a & b is an ... int. wtf. why?

Likewise byte & byte -> int.

This is specified in 5.6.2 Binary Numeric Promotion of the Java language specification.


(later:)
Its pointed out that C also does implicit casting of smaller types to int; but gcc is a little gentler with its warnings. a+b gives a warning (not an error) similar to the Java code above, but a&b does not (presumably because it knows that this can't make the number be any bigger than the types you started out with... something that gets lost in the Java type checking)

No comments:

Post a Comment