Xor for byte
Osvaldo Doederlein
opinali at gmail.com
Fri Jul 30 05:15:54 PDT 2010
The Java bytecode contains only the instructions ixor (for int) and
lxor (for long); it doesn't have specific opcodes for short- or
byte-xor. The same is true for several other operations, e.g. there's
no byte-mul bytecode so you cannot multiply bytes either, the compiler
will always report "cannot convert int to byte" because it promotes
the operands to int, then does an imul, which result is int.
IMHO this is a kind of tail-wags-dog situation, there's no reason why
the Java language should be constrained so much by the Java bytecode.
Recent syntax features (esp. post-Java5, but even some old stuff like
inner classes) require extensive workarounds to perform things that
the bytecode doesn't directly support. Maybe it's a good time to fix
the "little things", i.e.,
byte a, b, c;
c = a ^ b;
could easily be compiled with existing bytecode: just do the int->byte
narrowing implicitly. This narrowing is a no-brainer as the xor op
won't ever produce extra bits that don't fit in a byte.
The big problem is (as usual) backwards compatibility. If we try the
same change for multiplication, to accept "c = a * b", this will
potentially lose some bits because the result of the multiplication,
currently defined as a imul, may not fit in a byte (or short, for that
matter). This doesn't matter when the result is being assigned to a
byte lvalue like c; this requires to lose extra bits anyway, and it's
illegal (without explicit cast) in the current language so there's no
legacy code to break.
The problem though, is that there are certainly lots of legacy code like this:
byte a, b;
int c;
c = a * b;
...and such code, which IS legal in the current language, WOULD break
with a naive language change that just auto-narrows a * b to byte (or
short, for that matter, if the wider type of {a,b} is short).
But even this problem can be fixed, with target typing - a mechanism
that's being increasingly adopted by Java (due to needs of type
inference). This is quite simple: the compiler would only perform this
auto-narrowinfg when the result is immediately used in a context that
expects a byte. Then we're back to a scenario that contains a semantic
change, but only affects code that is currently illegal, so there's no
possible backwards-compat breakage.
A+
Osvaldo
2010/7/30 Franz Wong <franzwong at gmail.com>:
> Hi mailing list,
>
> I don't know if it is suitable to ask this question in this mailing list. I
> would like to ask why Java requires XOR for integer only instead of byte.
> Would it be better if XOR applies to byte also?
>
> Regards,
> Franz
>
>
More information about the coin-dev
mailing list