I have to admit in all my work with Java, I've never come across the need for a Java union (like the C union, not the SQL one) and I cannot find an answer here on SO. Admittedly, most of my work in Java has been at higher abstractions than bit-fiddling.
I have a integer which I'm setting individual bits for and I want to print out the equivalent IEEE754 single-precision float.
In C, I'd do something like:
union { int i; float f; } x; x.i = 0x27; printf ("%f\n", x.f);
How do I do a similar thing in Java? Is it even possible to treat the same memory as two different data types in Java?
I did search on both SO and elsewhere for "java union" but it swamped me with SQL stuff - I couldn't find a way to do this.
-------------Problems Reply------------
I have a integer which I'm setting individual bits for and I want to print out the equivalent IEEE754 single-precision float.
Use intBitsToFloat() for that.
Substitutes for Missing C Constructs
The designers of the Java programming language chose to omit the union construct because there is a much better mechanism for defining a single data type capable of representing objects of various types: subtyping. A discriminated union is really just a pallid imitation of a class hierarchy.
Includes examples.
Java doesn't provide any way to treat a value as another value on raw bit level - no unions, nothing like reinterpret_cast
. However, for your particular case of treating float
as int
and vice versa, you can use java.lang.Float.floatToIntBits
and intBitsToFloat
methods.
Some useful articles & faq to this subject are,
Union types in Java?
Substitutes for Missing C Constructs
If you are interested in accessing the bit-level representation of a float, java.lang.Double contains method to do this (doubleToLongBits etc.)
Union'ing between pointer types (or between pointers and their numeric represetantion) would open holes in the type system, so it is strictly impossible.