Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get/set individual bits in a float?

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.

like image 479
paxdiablo Avatar asked Aug 21 '09 07:08

paxdiablo


3 Answers

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.

like image 77
Michael Borgwardt Avatar answered Sep 18 '22 16:09

Michael Borgwardt


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.

like image 31
skaffman Avatar answered Sep 22 '22 16:09

skaffman


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.

like image 32
Pavel Minaev Avatar answered Sep 21 '22 16:09

Pavel Minaev