I have following code:
var packet = "\xFF\xFF\xFF\xFF";
packet += "\x6D";
packet += "127.0.0.1:" + this.port;
packet += "\x00";
packet += this.name;
packet += "\x00";
packet += this.state;
packet += "\x00";
packet += "stateA";
packet += "\x00";
packet += "sender";
packet += "\x00";
And I have var id = 32;
I want to get something like this:
...
packet += "\x00";
packet += "sender";
packet += "\x00";
packet += "\x20;
How to convert id number to HEX format and then concatenate it with packet?
I already saw Google, but I haven't found a solution.
Thank you.
You can use the toString() function of the Number prototype to get the hex representation of your number:
var hex = (23).toString( 16 );
// or
var hex = id.toString( 16 );
EDIT
It seems you just want to add a unicode symbol identified by id. For this use String.fromCharCode()
packet += String.fromCharCode( id );
You can use the String.fromCharCode function:
packet += String.fromCharCode(32); // " "
If you want to get the hex representation, you could use
var hex = (32).toString(16), // "20"
byte = JSON.parse('"\\u'+('000'+hex).slice(-4)+'"'); // " " == "\u0020"
…but that's ugly :-)
You can use String.fromCharCode(23) to do this.
E.G. (in a browser console):
> String.fromCharCode(23) == "\x17"
true
See JavaScript: create a string or char from an ASCII value for more general information.