JS-4 bytes to single precision floating point number

JS data type

JSIt 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 JavaScripthas 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 JavaScriptthese methods are ineffective (also, or I do not know how to turn too cai).

IEEE754It is now recognized as the most widely used standard floating-point conversion operation, by many CPUused by the floating point unit.

IEEEE475

Then we first look at IEEEE475the Floatformat, there is 32bitfor data storage, specific divided as follows:

Insert picture description here
Here we take 0x4128BC90as an example to explain:

0x4128BC90(H) = 01000001001010001011110010010000(B)

Sign (sign bit)

  • 0 Display positive number
  • 1 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)Exponent127

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

Guess you like

Origin blog.csdn.net/weixin_40774605/article/details/107323049