# JavaScript implements floating point Numbers to hexadecimal characters

• 2020-03-26 21:41:19
• OfStack

A recent embedded project requires WEB functions, so I thought of using HTML+JavaScript to achieve some parameter configuration functions. Parameters are generated by JavaScript in hexadecimal data, submitted to SCM through POST, and then used directly, in order to make full use of the computing power of the browser.

Because JavaScript support for floating point Numbers is very weak, the direct use of floating point Numbers turn hex function, double cannot achieve common in C language implementation of 4 bytes of storage format, through search, and didn't find the related function code, in the Node. Js Buffer class can implement this feature, but it can't use (single-chip storage co., LTD.), how didn't also the way to find the specific implementation (see don't know much about).

Such as:

0x42F6E979 in C, you can just convert a floating point number to an unsigned int and output it as a hexadecimal number, but in JavaScript the implementation is less straightforward.

Fortunately, I found an IEEE754 standard floating point conversion code (IEEE754 floating point converter (C# implementation) by clicking the open link), by converting this code into JavaScript, completed this work, for this purpose, the code posted, Shared.

In addition, I only managed to convert to 16, not reverse (reverse code) which is also available in C# code.

The following code can be achieved:
Get_float_hex (123.456) = = > 42 f6e979
``````
{
var bin = "";
var i;
for (i = 0; i < pad; i++)
{
dec *= 2;
if (dec>= 1)
{
dec -= 1;
bin += "1";
}
else
{
bin += "0";
}
}
return bin;
}
{
var bin="";
var i;
for (i = 0; i < pad; i++)
{
bin = (parseInt(dec % 2).toString()) + bin;
dec /= 2;
}
return bin;
}
function get_float_hex(decString)
{
var dec = decString;
var sign;
var signString;
var decValue = parseFloat(Math.abs(decString));
if (decString.toString().charAt(0) == '-')
{
sign = 1;
signString = "1";
}
else
{
sign = 0;
signString = "0";
}
if (decValue==0)
{
fraction = 0;
exponent = 0;
}
else
{
var exponent = 127;
if (decValue>=2)
{
while (decValue>=2)
{
exponent++;
decValue /= 2;
}
}
else if (decValue<1)
{
while (decValue < 1)
{
exponent--;
decValue *= 2;
if (exponent ==0)
break;
}
}
if (exponent!=0) decValue-=1; else decValue /= 2;

}
var fractionString = DecToBinTail(decValue, 23);