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,176
  • 3
  • 17
  • 35

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
  • 69,531
  • 19
  • 142
  • 174
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
  • 572,313
  • 128
  • 898
  • 1,281
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
  • 21,996
  • 7
  • 62
  • 87