javascript float from/to bits

后端 未结 5 1097
孤独总比滥情好
孤独总比滥情好 2020-12-01 09:50

I am trying to perform something that is brain-dead simple in any other language but not javascript: get the bits out of float (and the other way around).

In C/C++ i

5条回答
  •  天命终不由人
    2020-12-01 10:15

    1. JavaScript uses double (IEEE 754) to represent all numbers
    2. double consists of [sign, exponent(11bit), mantissa(52bit)] fields. Value of number is computed using formula (-1)^sign * (1.mantissa) * 2^(exponent - 1023). (1.mantissa - means that we take bits of mantissa add 1 at the beginning and tread that value as number, e.g. if mantissa = 101 we get number 1.101 (bin) = 1 + 1/2 + 1/8 (dec) = 1.625 (dec).
    3. We can get value of sign bit testing if number is greater than zero. There is a small issue with 0 here because double have +0 and -0 values, but we can distinguish these two by computing 1/value and checking if value is +Inf or -Inf.
    4. Since 1 <= 1.mantissa < 2 we can get value of exponent using Math.log2 e.g. Math.floor(Math.log2(666.0)) = 9 so exponent is exponent - 1023 = 9 and exponent = 1032, which in binary is (1032).toString(2) = "10000001000"
    5. After we get exponent we can scale number to zero exponent without changing mantissa, value = value / Math.pow(2, Math.floor(Math.log2(666.0))), now value represents number (-1)^sign * (1.mantissa). If we ignore sign and multiply that by 2^52 we get integer value that have same bits as 1.mantissa: ((666 / Math.pow(2, Math.floor(Math.log2(666)))) * Math.pow(2, 52)).toString(2) = "10100110100000000000000000000000000000000000000000000" (we must ignore leading 1).
    6. After some string concat's you will get what you want

    This is only proof of concept, we didn't discuss denormalized numbers or special values such as NaN - but I think it can be expanded to account for these cases too.

    @bensiu answers is fine, but if find yourself using some old JS interpreter you can use this approach.

提交回复
热议问题