Article Directory
JS data type
JS
It is a weakly typed language. Its data types include string values, numeric values, boolean values, arrays, and objects. Although our numeric types include floating point integers, etc., they are collectively referred to here 数值类型
. At the same time JavaScript
has a dynamic type, without specifying when we define the variable data type. This also means that our forced conversion will be invalid in JS.
If the C/C++
can be achieved by the conversion memory or complex. But JavaScript
these methods are ineffective (also, or I do not know how to turn too cai).
IEEE754
It is now recognized as the most widely used standard floating-point conversion operation, by many CPU
used by the floating point unit.
IEEEE475
Then we first look at IEEEE475
the Float
format, there is 32bit
for data storage, specific divided as follows:
Here we take 0x4128BC90
as an example to explain:
0x4128BC90(H) = 01000001001010001011110010010000(B)
Sign (sign bit)
0
Display positive number1
Represents a negative number
Exponent (exponent bit)
1000 0010(B) = 130 (D)
Significand (decimal places)
01010001011110010010000(B) = 0*2^(-1) + 1*2^(-2) + ... + 0*2^(-23)
Conversion formula
F u n ( x ) = ( − 1 ) S i g n × ( 1 + S i g n i f i c a n d ) × ( 2 ) E x p o n e n t − 127 Fun(x) = (-1)^{Sign} \times (1 + Significand) \times (2)^{Exponent - 127} Fun(x)=(−1)Sign×(1+Significand)×(2)Exponent−127
Conversion method
var bytes = new Array();
bytes[0] = 65;
bytes[1] = 40;
bytes[2] = 188;
bytes[3] = 144;
//IEEE754
function hex2float(num) {
//符号位
var sign = (num & 0x80000000) ? -1 : 1;
//指数位
var exponent = ((num >> 23) & 0xff) - 127;
//尾数位
var mantissa = 1 + ((num & 0x7fffff) / 0x7fffff);
return sign * mantissa * Math.pow(2, exponent);
}
//拼接为number对象
var mfloat = ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8) |
(bytes[3] & 0xFF);
console.log(hex2float(mfloat));
Online tools
The following are two online tools that I personally recommend that are very suitable for verification:
Float (IEEE754 Single precision 32-bit)
Online base converter_floating point conversion
Reference thanks
Converting hexadecimal to float in javascript
Computer Fundamentals-Conversion of IEEE754 Standard Floating Point Numbers