Skip to content

Instantly share code, notes, and snippets.

@stokito
Created October 8, 2018 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stokito/5f243c617973931fcc01d2718882654b to your computer and use it in GitHub Desktop.
Save stokito/5f243c617973931fcc01d2718882654b to your computer and use it in GitHub Desktop.
/**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