简体   繁体   English

如何在 JavaScript 中将数字表示为十六进制?

[英]How to represent number as hexadecimal in JavaScript?

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?有谁知道我哪里出错了?

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.只有 Number 的toString()方法会采用基数,String 不会。 Also, your result will be in lowercase, so you might want to force it to uppercase using toUpperCase() :此外,您的结果将为小写,因此您可能希望使用toUpperCase()将其强制为大写:

function d2h(d) { return (+d).toString(16).toUpperCase(); }

So the result will be:所以结果将是:

d2h("28") //is "1C"

Duplicate question重复问题

(28).toString(16)

The bug you are making is that "28" is a string, not a number.您正在制造的错误是“28”是一个字符串,而不是一个数字。 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).人们通常不应该期望语言能够在进行转换之前将字符串解析为整数(嗯......我想在 javascript 中期望相反是合理的)。

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。

let returnedHex = Number(var_value).toString(16);

也有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM