2

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?

1

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thats exactly what I wanted! Bravo! :-)
You don't need to add 0x before an hexadecimal value to parse it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.