More Fun with Bits

The method below multiplies a float by 2 by manipulating its bits to increment the exponent. See the javadoc for Float.intBitsToFloat() for details on the IEEE754 floating-point representation. Unlike the previous blog entry, the methods used here have been around a long time.

static float multiplyByTwo(float x) {
    // View the float as 32 bits
    int bits = Float.floatToIntBits(x);
    // Extract the bits that represent the exponent
    int exponent = (bits >> 23) & 0xFF;
    // clear the exponent bits
    bits &= ~(0xFF << 23);
    // Increment the exponent and set this new value
    bits |= ((exponent+1) & 0xFF) << 23;
    // Return the bits as a float
    return Float.intBitsToFloat(bits);
}

Books

ECMAScript 5 & HTML5!

"A must-have reference"
Brendan Eich,
creator of JavaScript

JavaScript graphics makes web programming fun again!

Read Less, Learn More

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

The classic Java quick-reference

About

Advertising

Pages

Hosted By

Powered by Movable Type 4.21-en