5

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?

6
  • @Chuck nope that does not cut it^^ Commented Apr 17, 2014 at 0:09
  • how does that not cut it? Commented Apr 17, 2014 at 0:14
  • 1
    are you seriously having problems add \x to the hex number? Commented Apr 17, 2014 at 0:15
  • @KeithNicholas No, but I have a problem understanding it, there seems to be a difference between \x2 and \x02. And how can I now that 0x0062 is \x62 as string. Commented Apr 17, 2014 at 0:19
  • 1
    Leading zeroes in hexadecimal don't make any numeric difference. 9 == 09 == 009 == 0009… ad infinitum. I think whatever service you're giving the string to is just a little bit eccentric. Commented Apr 17, 2014 at 0:37

3 Answers 3

15

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
Sign up to request clarification or add additional context in comments.

8 Comments

It has to be in "\x62" format.
a = 64; a = '\x' + a.toString(16);
you can easily concatenate that.
Doesn't work with 2 as the OP explicitly required the function to return \x02 and not \x2
|
3

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.

4 Comments

What if number = 2? hexStr would be \x2, but should be \x02
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.
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...
You're asking about JS, ok never mind. Just add var hexStr = '\x0' + number.toString(16);
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.