一、浮点转16进制数据
//浮点数转16进制
function singleToHex( t) { if ( t == "" ) { return "" ; } t = parseFloat( t.substr( 0 , 4 )) ; if ( isNaN( t) == true ) { return "Error" ; } if ( t == 0 ) { return "00000000" ; } var s,e,m; if ( t > 0 ) { s = 0 ; } else { s = 1 ; t = 0 - t; } m = t.toString( 2 ) ; if ( m >= 1 ) { if ( m.indexOf( "." ) == -1) { m = m + ".0" ; } e = m.indexOf( "." ) - 1 ; } else { e = 1 - m.indexOf( "1" ) ; } if ( e >= 0 ) { m = m.replace( "." , "" ) ; } else { m = m.substring( m.indexOf( "1" )) ; } if ( m.length > 24 ) { m = m.substr( 0 , 24 ) ; } else { m = FillString( m, "0" , 24 , false ) } m = m.substring( 1 ) ; e = ( e + 127 ) .toString( 2 ) ; e = FillString( e, "0" , 8 , true ) ; var r = parseInt( s + e + m, 2 ) .toString( 16 ) ; r = FillString( r, "0" , 8 , true ) ; var value = InsertString( r, " " , 2 ) .toUpperCase( ) ; return value.substr( 6 , 2 ) + value.substr( 9 , 2 ) + value.substr( 0 , 2 ) + value.substr( 3 , 2 )
}
二、16进制转浮点(单精度)
//16进制转浮点数( 单精度)
function HexToDouble( hex) { let S, E, M, result; S = hex >> > 31 ; E = (( hex << 1 ) >> > 24 ) ; M = ( hex << 9 ) >> > 9 ; if ( E == = 0xff ) {if ( M == = 0x0 ) {return (( - 1 ) ** S) * Infinity; } else {return NaN; }}result = (( - 1 ) ** S) * ( M / ( 1 << 23 ) + ! ! ( E)) * ( 2 ** ( E - 127 + ! E)) ; return result;
}
三、16进制转浮点(双精度)
//16进制转浮点数( 双精度)
function hexToSingle( t, fixed = 2 ) { t = t.replace( /\ s+/g, "" ) ; if ( t == "" ) { return "" ; } if ( t == "00000000" ) { return "0" ; } if (( t.length > 8 ) || ( isNaN( parseInt( t, 16 )) )) { return "Error" ; } if ( t.length < 8 ) { t = FillString( t, "0" , 8 , true ) ; } t = parseInt( t, 16 ) .toString( 2 ) ; t = FillString( t, "0" , 32 , true ) ; var s = t.substring( 0 , 1 ) ; var e = t.substring( 1 , 9 ) ; var m = t.substring( 9 ) ; e = parseInt( e, 2 ) - 127 ; m = "1" + m; if ( e >= 0 ) { m = m.substr( 0 , e + 1 ) + "." + m.substring( e + 1 ) } else { m = "0." + FillString( m, "0" , m.length - e - 1 , true ) } if ( m.indexOf( "." ) == -1) { m = m + ".0" ; } var a = m.split( "." ) ; var mi = parseInt( a[ 0 ] , 2 ) ; var mf = 0 ; for ( var i = 0 ; i < a[ 1 ] .length; i++) { mf += parseFloat( a[ 1 ] .charAt( i)) * Math.pow( 2 , -( i + 1 )) ; } m = parseInt( mi) + parseFloat( mf) ; if ( s == 1 ) { m = 0 - m; } if ( fixed) { m = m.toFixed( fixed) .replace( /[ .] ?0+$/, "" ) } return m;
}