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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With