1

In Javascript, how do I convert a string representation of a hex value into it's hex representation ?

What I have returning from a checksum routine is a string value "FE". What I need is it's hex representation "\xFE"

I cannot simply do this, as it gives me an error:

var crc = "FE";
var hex = "\x" + crc;

This just gives me a new 4 character ASCII string:

var crc = "FE";
var hex = "0x" + "FE";

thxs for any guidance.

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Bruiser
  • 11
  • 2
  • I think you have to use [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) – hindmost Oct 10 '14 at 14:22
  • 1
    It's not clear what you want. Do you want the string "\xFE"? Or an int having a value of 0xFE? – michaelgulak Oct 10 '14 at 14:24
  • possible duplicate of [How to convert decimal to hex in JavaScript?](http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript) – Ben Oct 10 '14 at 14:25
  • `'FE'` *already is* is the hex representation of a number. What exactly do you want now? – Felix Kling Oct 10 '14 at 14:28
  • Maybe this `"FE" -> "\u00FE" -> "þ"` ? – Andreas Louv Oct 10 '14 at 14:34
  • I ended up figuring it out: var crc = "FE"; var hex = String.fromCharCode(parseInt(crc),16)); – Bruiser Oct 10 '14 at 15:00
  • Wow, I would never have guessed that that's what you want, given the problem description. Care to update your question and make it clearer? – Felix Kling Oct 11 '14 at 01:01

2 Answers2

3

like this

var hex = parseInt("FF", 16);
Ben
  • 3,569
  • 6
  • 45
  • 77
0

For the string \xFE, escape the backslash: var hex = '\\x'+'FE'

To convert 'FE' to a Number use +('0xFE')

To show +('0xFE') as a hexadecimal, use (224).toString(16), or '0x'+((254).toString(16))

KooiInc
  • 112,400
  • 31
  • 139
  • 174
  • or `(123).toString(16)` or `var a = 123; a.toString(16)`. While `123.toString` will throw an error because the compiler will think you are about to write a float instead of an int. This will also work: `123 .toString` (Notice the space) – Andreas Louv Oct 10 '14 at 14:39