Alex Aly
Alex Aly

Reputation: 46

Float as integer binary conversion

I have this problem regarding conversion:

I have an integer, but I know it represents a float. Here are some correspondence examples:

Integer Float
16256 1.00
16262 1.05
16291 1.28
16298 1.33

My question is: what is the algorithm for this type of conversion? How can you get the float value if you read the bytes as integer with 32 bit?

I then want to write a function that returns the integer for that said float.

I'm not using any language. I'm using a cheat engine in a game and found out that 100 ingame translates to 16256, and so on by changing the values inside the game I get the values inside the cheat engine, I'm trying to write a converter to make my search easier.

Upvotes: 0

Views: 193

Answers (1)

trincot
trincot

Reputation: 350310

This looks like a 16-bit float representation with:

  • 1 sign bit
  • 8 exponent bits, with 127 bias
  • 7 mantissa bits, with leading bit convention

It is known as the bfloat16 floating point format.

If this is correct, then here is a basic implementation in JavaScript to translate the 16-bit integer to its intended interpretation:

function asFloat(i) {
    let mantissa = i & 0x7F;
    let exponent = (i >> 7) & 0xFF;
    let negative = i >= 0x8000;
    
    // Remove exponent bias and add hidden bit to mantissa
    let result = (1.0 + mantissa / 128.0) * 2 ** (exponent - 127);
    return negative ? -result : result;
}

console.log(asFloat(16256));
console.log(asFloat(16298));

Note that for this "short" float, the above snippet prints too many digits, as really this 16-bit float format cannot represent that level of precision. 1.3333333 cannot be faithfully represented in a float data type, and the shorter the float format is, the less accurate it will be.

The inverse function could look like this:

function asInt(f) {
    if (f < 0) return 0x8000 + asInt(-f);
    let exponent = Math.floor(Math.log2(f));
    let mantissa = Math.floor((f / 2**exponent - 1) * 128);
    return ((exponent + 127) << 7) + mantissa;
}

console.log(asInt(1));
console.log(asInt(1.33333));

Upvotes: 2

Related Questions