简体   繁体   中英

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. 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.

An example of a string would be: 00010203040506070809

I am having a hard time converting it to: 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM