将hexstring转换为BYTE数组JS
我一直在这一点,我是与JS编程新。 我正在使用JS,HTML5,节点和socket.io进行游戏。 我现在正在协议,我发送hex的服务器string。
一个string的例子是:00010203040506070809
我很难将其转换为:0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
我打算做的是采取这些自定义数据包,并根据数据包在我的服务器上有一个开关。 举个例子:
BYTE HEADER | + Packet 0x00 | 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
然后我调用: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; } };
有谁知道如何做到这一点?
我不确定这是什么,但你可以将string转换为一个hex值的数组,如下所示:
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