admin管理员组

文章数量:1406924

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.

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.

Share Improve this question asked May 17, 2013 at 14:31 user0103user0103 1,2723 gold badges18 silver badges36 bronze badges 7
  • How to convert decimal to hex in javascript – jonhopkins Commented May 17, 2013 at 14:34
  • possible duplicate of How to convert decimal to hex in JavaScript? – TheHippo Commented May 17, 2013 at 14:39
  • 2 Why are you using strings and not buffers? – Benjamin Gruenbaum Commented May 17, 2013 at 14:42
  • possible duplicate of JavaScript: create a string or char from an ASCII value – Bergi Commented May 17, 2013 at 14:44
  • @BenjaminGruenbaum I'm creating buffers from string. – user0103 Commented May 17, 2013 at 14:47
 |  Show 2 more ments

3 Answers 3

Reset to default 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 );

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 How to create a string or char from an ASCII value in JavaScript? for more general information.

本文标签: javascriptBinary concatenationStack Overflow