Javascript 将十六进制 ASCII 解析为数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1981760/
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
Parse HEX ASCII into numbers?
提问by Paul
I have a H/W device that normally uses a serial port for an interface, sending and receiving binary messages to a PC UI program. I've added an Ethernet port and small TCP/IP stack with a small web server that I want to use to replace the serial port UI with a web browser UI.
我有一个硬件设备,它通常使用串行端口作为接口,向 PC UI 程序发送和接收二进制消息。我添加了一个以太网端口和一个带有小型 Web 服务器的小型 TCP/IP 堆栈,我想用它来用 Web 浏览器 UI 替换串行端口 UI。
The messages are mostly request/response sort of things, but for some web pages I may need to Tx/Rx two or more messages to get all the info I need for the page. I'll use the AJAX XMLHttpRequest() to send the messages and get the responses for a page.
消息主要是请求/响应之类的东西,但对于某些网页,我可能需要 Tx/Rx 两条或更多条消息来获取页面所需的所有信息。我将使用 AJAX XMLHttpRequest() 发送消息并获取页面的响应。
The H/W device has limited resources (CPU & RAM) so to keep it simple on that end I want to just make a little CGI interface that takes outgoing messages and encodes them as HEX ASCII (i.e. two HEX ASCII chars/byte) to send to the browser which will use some java script to pick apart the messages into fields and convert them to numeric vars and display them to the user. Same for messages sent from the browser to the H/W device.
H/W 设备的资源(CPU 和 RAM)有限,因此为了保持简单,我只想制作一个小的 CGI 接口,用于接收传出消息并将它们编码为 HEX ASCII(即两个 HEX ASCII 字符/字节)以发送到浏览器,浏览器将使用一些 java 脚本将消息分成字段并将它们转换为数字变量并将它们显示给用户。从浏览器发送到硬件设备的消息也是如此。
Messages contain a mixture of field types, signed & unsigned bytes, shorts, longs, floats, and are futher complicated by being mostly in little endian byte order in the messages.
消息包含字段类型、有符号和无符号字节、shorts、longs、floats 的混合,并且由于在消息中主要采用小端字节序而更加复杂。
I can handle the H/W end code, but I'm struggling to learn java script and could use help with a function to translate the HEX ASCII <-> numerics on the browser end.
我可以处理 H/W 结束代码,但我正在努力学习 Java 脚本,并且可以使用函数帮助来转换浏览器端的 HEX ASCII <-> 数字。
Any ideas? Any example code some where?
有任何想法吗?任何示例代码在哪里?
Thanks, Paul
谢谢,保罗
回答by Brian Campbell
Sounds like you want parseInt. It takes a string and an optional radix (which should always be supplied), and parses the number as an integer in that radix (or a radix based on the format of the number if none is supplied, which is why you should always supply one; people are surprised to find that parseInt("010")returns 8).
听起来你想要parseInt。它接受一个字符串和一个可选的基数(应始终提供),并将该数字解析为该基数中的整数(或基于数字格式的基数,如果没有提供,这就是为什么你应该总是提供一个; 人们惊讶地发现parseInt("010")返回8)。
> parseInt("ab", 16)
171
To convert back to hex, you can use toString:
要转换回十六进制,您可以使用toString:
> var num = 16
> num.toString(16)
"10"
Note that you will have to pad it out to two characters yourself if it comes out as only a single character:
请注意,如果它仅作为单个字符出现,则您必须自己将其填充为两个字符:
> num = 5
> num.toString(16)
"5"
I was bored, so I wrote some functions to do the conversion in both directions for you:
我很无聊,所以我写了一些函数来为你做双向转换:
function parseHexString(str) {
var result = [];
// Ignore any trailing single digit; I don't know what your needs
// are for this case, so you may want to throw an error or convert
// the lone digit depending on your needs.
while (str.length >= 2) {
result.push(parseInt(str.substring(0, 2), 16));
str = str.substring(2, str.length);
}
return result;
}
function createHexString(arr) {
var result = "";
for (i in arr) {
var str = arr[i].toString(16);
// Pad to two digits, truncate to last two if too long. Again,
// I'm not sure what your needs are for the case, you may want
// to handle errors in some other way.
str = str.length == 0 ? "00" :
str.length == 1 ? "0" + str :
str.length == 2 ? str :
str.substring(str.length-2, str.length);
result += str;
}
return result;
}
Which can be used as follows:
可以按如下方式使用:
> parseHexString("abcd100001")
[171, 205, 16, 0, 1]
> createHexString([0, 1, 2, 10, 20, 100, 200, 255, 1000, 2000])
"0001020a1464c8ffe8d0"
> parseHexString(createHexString([0, 1, 2, 10, 20, 100, 200, 255, 1000, 2000]))
[0, 1, 2, 10, 20, 100, 200, 255, 232, 208]
回答by J.J.
You're looking for the parseInt()function:
您正在寻找parseInt()功能:
x = "0xff";
y = parseInt(x, 16);
alert(y); //255
回答by Michel Gokan
did you looking for something like these 2 functions ?
您是否正在寻找类似这两个功能的东西?
<html>
<head>
<script type="text/javascript">
function hex2Decimal( hex )
{
return parseInt("0x"+hex);
}
function decimal2Hex( num )
{
return num.toString(16);
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(hex2Decimal("A") + "<br />");
document.write(decimal2Hex(16) + "<br />");
</script>
</body>
</html>

