1

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.

user0103
  • 1,246
  • 3
  • 18
  • 36

3 Answers3

4

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 );
Sirko
  • 72,589
  • 19
  • 149
  • 183
2

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 :-)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can use String.fromCharCode(23) to do this.

E.G. (in a browser console):

> String.fromCharCode(23) == "\x17"
true

See How to create a string or char from an ASCII value in JavaScript? for more general information.

Community
  • 1
  • 1
intuited
  • 23,174
  • 7
  • 66
  • 88