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
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
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
, andNaN
(not-a-number).
You can convert the given hex string with parseInt(string, radix)
to a decimal integer representation.
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)