[英]Converting a hex string into a BYTE array JS
我已經有一段時間了,對JS編程我還是陌生的。 我正在使用JS,HTML5,node和socket.io制作游戲。 我現在正在研究協議,並且正在發送十六進制的服務器字符串。
字符串的示例為: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;
}
};
有誰知道如何做到這一點?
我不確定這是您要執行的操作,但是您可以將字符串轉換為十六進制值的數組,如下所示:
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.