简体   繁体   English

如何将十进制转换为十六进制,以便结果是数字而不是字符串?

[英]How to convert decimal to hexadecimal so that the result is a number and not a string?

I am manually sending numbers to an arduino board as hexadecimal like this: sendToBoard(0xE) I am now trying to get decimal numbers converted into hexadecimal, but I can only get strings我正在手动将十六进制数字发送到 arduino 板,如下所示: sendToBoard(0xE)我现在正在尝试将十进制数字转换为十六进制,但我只能获取字符串

const number = 14
number.toString(16) //e  --> string

Could I possibly get this 'e' as hexadecimal to send it to the board like sendToBoard(number) //number === e (in hex)我能不能把这个'e'作为十六进制发送到板上,比如sendToBoard(number) //number === e (in hex)

In Javascript numbers are implemented using double-precision 64-bit binary format .在 Javascript 中,数字是使用双精度 64 位二进制格式实现的。 So even if you present them in hexadecimal format, under the hood they will be saved using floating-point representation.因此,即使您以十六进制格式显示它们,在后台它们也将使用浮点表示进行保存。

if you have a number and you want the sendToBoard function to receive a number as its input, then just pass in the number:如果您有一个数字并且您希望sendToBoard function 接收一个数字作为其输入,那么只需传入该数字:

function sendToBoard(number){
    // you can later convert it to a string:
    const str = '0x' + number.toString(16).toUpperCase();
}

Alternatively, if you have a string in a hexadecimal representation, and you want sendToBoard to receive a number type, you could do the following:或者,如果您有一个十六进制表示的字符串,并且您希望sendToBoard接收数字类型,您可以执行以下操作:

const number = parseInt('0xf', 16);
sendToBoard(number);

Hope this helps:)希望这可以帮助:)

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

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