javascript 将十六进制字符串转换为 BYTE 数组 JS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10121507/
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 a hex string into a BYTE array JS
提问by user1328762
I have been at this for a bit, and I am new to programing with JS. I am making a game using JS, HTML5, node and socket.io. I am working on the protocol right now and I am sending the server strings that are hex.
我已经在这方面工作了一段时间,而且我是使用 JS 编程的新手。我正在使用 JS、HTML5、node 和 socket.io 制作游戏。我现在正在研究协议,我正在发送十六进制的服务器字符串。
An example of a string would be: 00010203040506070809
一个字符串的例子是:00010203040506070809
I am having a hard time converting it to: 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
我很难将它转换为:0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
What I plan on doing is taking these custom packets and having a switch on my server based on the packets. So for example:
我打算做的是获取这些自定义数据包,并根据数据包在我的服务器上设置一个交换机。例如:
BYTE HEADER | + Packet
0x00 | 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
Then I call: parsepacket(header, data, len);
然后我调用: parsepacket(header, data, len);
function parsepacket(header, data, len){
switch(header)
{
case '0x00': // not hexed
console.log('The client wants to connect');
// Do some stuff to connect
break;
case '0x01':
console.log('0x01');
break;
case '0x02':
console.log('0x02!');
break;
}
};
Does anyone know how to do this?
有谁知道如何做到这一点?
回答by Joel Lundberg
I'm not sure this is what you're after, but you can convert the string to an array of hex values like this:
我不确定这是您想要的,但您可以将字符串转换为十六进制值数组,如下所示:
var str = "00010203040506070809",
a = [];
for (var i = 0; i < str.length; i += 2) {
a.push("0x" + str.substr(i, 2));
}
console.log(a); // prints the array
console.log(a.join(" ")); // turn the array into a string of hex values
?console.log(parseInt(a[1], 16));? // parse a particular hex number to a decimal value