javascript 在javascript中将十六进制转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5055723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting hexadecimal to float in javascript
提问by naveen
This questionmade me ask the below question.
这个问题让我问了下面的问题。
I would like to convert a number in base 10 with fraction to a number in base 16.
我想将带分数的以 10 为基数的数字转换为以 16 为基数的数字。
var myno = 28.5;
var convno = myno.toString( 16 );
alert( convno );
all is well there. now i want to convert it back to decimal.
But now I cannot write
一切都很好。现在我想将它转换回十进制。
但现在我不能写
var orgno = parseInt( convno, 16 );
alert( orgno );
As it doesn't return the decimal part.
因为它不返回小数部分。
And cannot use parseFloat, since per MDC the syntax of parseFloat is
并且不能使用 parseFloat,因为每个 MDC parseFloat 的语法是
parseFloat(str);
It wouldn't have been a problem if I had to convert back to int, since parseInt syntax is
如果我必须转换回 int 不会有问题,因为 parseInt 语法是
parseInt(str [, radix]);
So what is an alternative for this?
那么有什么替代方案呢?
Disclaimer: I thought it was a trivial question but googling gave me no answers.
免责声明:我认为这是一个微不足道的问题,但谷歌搜索没有给我答案。
采纳答案by Kent
Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together.
另一种可能性是分别解析数字,将字符串分成两部分,并在转换过程中将这两个部分都视为整数,然后将它们加在一起。
function parseFloat(str, radix)
{
var parts = str.split(".");
if ( parts.length > 1 )
{
return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length);
}
return parseInt(parts[0], radix);
}
var myno = 28.4382;
var convno = myno.toString(16);
var f = parseFloat(convno, 16);
alert(myno + " -> " + convno + " -> " + f );
回答by Asler
Try this.
试试这个。
string may be raw data(simple text) with 4 chars(0 - 255) or hex string "0xffffffff" 4 bytes length
字符串可以是具有 4 个字符(0 - 255)或 16 进制字符串“0xffffffff”的原始数据(简单文本),长度为 4 个字节
var str = '0x3F160008';
function parseFloat(str) {
var float = 0, sign, order, mantiss,exp,
int = 0, multi = 1;
if (/^0x/.exec(str)) {
int = parseInt(str,16);
}else{
for (var i = str.length -1; i >=0; i -= 1) {
if (str.charCodeAt(i)>255) {
console.log('Wrong string parametr');
return false;
}
int += str.charCodeAt(i) * multi;
multi *= 256;
}
}
sign = (int>>>31)?-1:1;
exp = (int >>> 23 & 0xff) - 127;
mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
for (i=0; i<mantissa.length; i+=1){
float += parseInt(mantissa[i])? Math.pow(2,exp):0;
exp--;
}
return float*sign;
}
回答by Kevin Smith
I combined Mark's and Kent's answers to make an overloaded parseFloat function that takes an argument for the radix (much simpler and more versatile):
我结合 Mark 和 Kent 的答案来制作一个重载的 parseFloat 函数,该函数接受基数的参数(更简单,更通用):
function parseFloat(string, radix)
{
//split the string at the decimal point
string = string.split(/\./);
//if there is nothing before the decimal point, make it 0
if (string[0] == '') {
string[0] = "0";
}
//if there was a decimal point & something after it
if (string.length > 1 && string[1] != '') {
var fractionLength = string[1].length;
string[1] = parseInt(string[1], radix);
string[1] *= Math.pow(radix, -fractionLength);
return parseInt(string[0], radix) + string[1];
}
//if there wasn't a decimal point or there was but nothing was after it
return parseInt(string[0], radix);
}
I hope this helps someone!
我希望这可以帮助别人!
回答by Mark Eirich
Please try this:
请试试这个:
function hex2dec(hex) {
hex = hex.split(/\./);
var len = hex[1].length;
hex[1] = parseInt(hex[1], 16);
hex[1] *= Math.pow(16, -len);
return parseInt(hex[0], 16) + hex[1];
}
回答by awm
Try this:
试试这个:
- Decide how many digits of precision you need after the decimal point.
- Multiply your original number by that power of 16 (e.g. 256 if you want two digits).
- Convert it as an integer.
- Put the decimal point in manually according to what you decided in step 1.
- 确定小数点后需要多少位精度。
- 将您的原始数字乘以 16 的幂(例如,如果您想要两位数,则为 256)。
- 将其转换为整数。
- 根据您在步骤 1 中的决定手动输入小数点。
Reverse the steps to convert back.
反转步骤以转换回来。
- Take out the decimal point, remembering where it was.
- Convert the hex to decimal in integer form.
- Divide the result by the the appropriate power of 16 (16^n, where n is the number of digits after the decimal point you took out in step 1).
- 取出小数点,记住它的位置。
- 以整数形式将十六进制转换为十进制。
- 将结果除以 16 的适当幂(16^n,其中 n 是您在步骤 1 中取出的小数点后的位数)。
A simple example:
一个简单的例子:
Convert decimal 23.5 into hex, and want one digit after the decimal point after conversion.
将十进制23.5转换成十六进制,转换后要小数点后一位。
23.5 x 16 = 376.
23.5 x 16 = 376。
Converted to hex = 0x178.
转换为十六进制 = 0x178。
Answer in base 16: 17.8
以 16 为底的答案:17.8
Now convert back to decimal:
现在转换回十进制:
Take out the decimal point: 0x178
取出小数点:0x178
Convert to decimal: 376
转换为十进制:376
Divide by 16: 23.5
除以 16:23.5
回答by Zajec
I'm not sure what hexadecimal format you wanted to parse there, was this something like: "a1.2c"?
我不确定你想在那里解析什么十六进制格式,是这样的:“a1.2c”?
Floats are commonly stored in hexadecimal format using IEEE 754 standard. That standard doesn't use any dots (which don't exist in pure hexadecimal alphabet). Instead of that there are 3 groups of bits of predefined length (1 + 8 + 23 = 32bits in total ─ double uses 64bits).
浮点数通常使用IEEE 754 标准以十六进制格式存储。该标准不使用任何点(纯十六进制字母表中不存在)。取而代之的是,有 3 组预定义长度的位(1 + 8 + 23 = 总共 32 位 - double 使用 64 位)。
I've written the following function for parsing such a numbers into float:
我编写了以下函数来将此类数字解析为浮点数:
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);
}

