Javascript 如何在javascript中将DEC转换为HEX?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12291755/
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
How to convert DEC to HEX in javascript?
提问by Aaron
I am trying to convert a DEC number to HEX using JavaScript.
我正在尝试使用 JavaScript 将 DEC 数字转换为 HEX。
The number I am trying to convert is 28.
我要转换的数字是 28。
I have tried using:
我试过使用:
function h2d(h) {return parseInt(h,16);}
however it returns 40
但是它返回 40
I have also tried using:
我也试过使用:
function d2h(d) {return d.toString(16);}
however it returns 28
但是它返回 28
The final result should return 1C but I can't seem to work it out.
最终结果应该返回 1C,但我似乎无法解决。
Does anyone know where I have gone wrong?
有谁知道我哪里出错了?
回答by Pete
It sounds like you're having trouble because your input is a String when you're looking for a number. Try changing your d2h() code to look like this and you should be set:
听起来您遇到了麻烦,因为您在查找数字时输入的是字符串。尝试将 d2h() 代码更改为如下所示,您应该设置:
function d2h(d) { return (+d).toString(16); }
The plus sign (+
) is a shorthand method for forcing a variable to be a Number. Only Number's toString()
method will take a radix, String's will not. Also, your result will be in lowercase, so you might want to force it to uppercase using toUpperCase()
:
加号 ( +
) 是强制变量为数字的速记方法。只有 Number 的toString()
方法会采用基数,String 的不会。此外,您的结果将为小写,因此您可能希望使用toUpperCase()
以下命令将其强制为大写:
function d2h(d) { return (+d).toString(16).toUpperCase(); }
So the result will be:
所以结果将是:
d2h("28") //is "1C"
回答by ninjagecko
Duplicate question
重复问题
(28).toString(16)
The bug you are making is that "28" is a string, not a number. You should treat it as a number. One should not generally expect the language to be able to parse a string into an integer before doing conversions (well... I guess it's reasonable to expect the other way around in javascript).
您正在制造的错误是“28”是一个字符串,而不是一个数字。你应该把它当作一个数字。人们通常不应该期望语言能够在进行转换之前将字符串解析为整数(嗯......我想在 javascript 中期望相反是合理的)。
回答by Mark Reed
d2h() as written should work fine:
所写的 d2h() 应该可以正常工作:
js> var d=28
js> print(d.toString(16))
1c
How did you test it?
你是怎么测试的?
Also, 40 is the expected output of d2h(28), since hexadecimal "28" is decimal 40.
此外,40 是 d2h(28) 的预期输出,因为十六进制“28”是十进制 40。