3

I want to convert an number (integer) to a hex string

2 (0x02) to "\x02"

or

62 (0x0062) to "\x62"

How can I do that correctly?

UpCat
  • 67,448
  • 127
  • 369
  • 590

3 Answers3

13

You can use the to string method:

a = 64;
a.toString(16); // prints "40" which is the hex value
a.toString(8); // prints "100" which is the octal value
a.toString(2); // prints "1000000" which is the binary value
Ibu
  • 41,298
  • 13
  • 73
  • 100
2

Well, it's seems that you want just to concatenate the integer with \x.

If so just to like that:

var number = 62;
var hexStr = '\x' + number.toString(16);

But you have something strange about explaining.

Note: that 62 is not the same as 0x62, 0x62 would be 98.

volter9
  • 717
  • 5
  • 16
  • What if number = 2? hexStr would be \x2, but should be \x02 – UpCat Apr 17 '14 at 00:21
  • But what the difference? The value still would be 2. If you need so I'll give you the answer, but there's no difference. – volter9 Apr 17 '14 at 00:22
  • If I would do this in python I would get "invalid \x escape' while \x02 would be excepted, so there seems to be a difference... – UpCat Apr 17 '14 at 00:25
  • You're asking about JS, ok never mind. Just add `var hexStr = '\x0' + number.toString(16);` – volter9 Apr 17 '14 at 00:26
1

var converted = "\x" + number.toString(16)

Neel
  • 597
  • 4
  • 19