25

Hey all i am in need of something simple to convert character(s) into ASCII and then make that into a Hex code.

So as an example the "A" character would be:

0xF100 + ascii_code = Hex

and that would turn out to be:

0xF100 + 65 = 0xF141

65 would be the character "A" above. I've been looking for some javascript that would take my character and make a Hex from it... But i haven't really found anything that would do this....

Any help would be great!

1
  • Why would you be doing this? 0xF141 is a Private Use code point and should not be used in public information interchange but only by private agreements. There is probably a more reasonable approach to the original problem, whatever it is. Commented Dec 14, 2013 at 8:05

1 Answer 1

53

Number's toString accepts a radix parameter, with which you can convert the ASCII code to hexadecimal like this:

var data = "A";
console.log("0xF1" + data.charCodeAt(0).toString(16));

16 means base 16, which is hexadecimal.

5
  • 2
    What does the (16) do?
    – StealthRT
    Commented Dec 14, 2013 at 5:41
  • 3
    @StealthRT 16 means base 16, which is hexadecimal. Commented Dec 14, 2013 at 5:41
  • 1
    you can also do .toString(36) which is base 36 which includes letters past 9. I think .toString(2) is to binary.
    – etoxin
    Commented Aug 20, 2014 at 6:54
  • .toString(10) is decimal
    – swade
    Commented Jan 28, 2016 at 23:36
  • 4
    Just to alert you, if your string contains any character codes below 16, an extra step is needed to zero pad. An example if how to do this is var c = a.charCodeAt(i);var d = "00"+c.toString(16);var e = d.substr(d.length-2); Commented Aug 23, 2016 at 22:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.