[英]Converting a hex string into a BYTE array JS
I have been at this for a bit, and I am new to programing with JS. 我已经有一段时间了,对JS编程我还是陌生的。 I am making a game using JS, HTML5, node and socket.io. 我正在使用JS,HTML5,node和socket.io制作游戏。 I am working on the protocol right now and I am sending the server strings that are hex. 我现在正在研究协议,并且正在发送十六进制的服务器字符串。
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? 有谁知道如何做到这一点?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.