0

I want to convert a byte in String representation, for example:

"FF"

To a real byte representation:

0xFF

Other examples:

"00" to 0x00

"10" to 0x10

"2A" to 0x2A

"5F" to 0x5F

and so on...

How can I do this?

Thanks

2 Answers2

0

Javascript has no data type hex, or similar.

Number type

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (number between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

You can convert the given hex string with parseInt(string, radix) to a decimal integer representation.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

If it is definetelly 2 characters length here is a function that you need:

function stringToByte (str) {
  str = str.toUpperCase()
  var codes = [str.charCodeAt(0), str.charCodeAt(1)]
  for (var i = 0; i < 2; i++) {
    if (codes[i] >= 48 && codes[i] <= 57) {
      codes[i] -= 48
    } else {
      codes[i] -= 55
    }
  }
  return codes[0] * 16 + codes[1]
}
console.log(stringToByte('00') === 0x00, stringToByte('FF') === 0xFF)
Nick Messing
  • 494
  • 5
  • 14