Created
October 8, 2018 15:28
-
-
Save stokito/5f243c617973931fcc01d2718882654b to your computer and use it in GitHub Desktop.
Float represenation in Java https://stackoverflow.com/questions/24273994/how-do-you-get-the-mantissa-of-a-float-in-java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.*/ | |
void floatDestuct() { | |
int bits = Float.floatToIntBits(-0.005f); | |
int sign = bits >>> 31; | |
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1); | |
int mantissa = bits & ((1 << 23) - 1); | |
System.out.println(sign + " " + exp + " " + mantissa + " " + | |
Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa)); | |
} | |
/** The same approach can be used for double’s (11 bit exponent and 52 bit mantissa) */ | |
void doubleDestuct() { | |
long bits = Double.doubleToLongBits(-0.005); | |
long sign = bits >>> 63; | |
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1); | |
long mantissa = bits & ((1L << 52) - 1); | |
System.out.println(sign + " " + exp + " " + mantissa + " " + | |
Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment