I was having the same problem. I had a string, let's say "CA030101CF", and I wanted to convert it to hexadecimal values, like 0xCA 0x03 0x01 0x01 0xCF. To be clear, not a string looking like hexadecimal values. It means 0xCA, not '0xCA' and so on.
Finally, the solution that worked for me was using the Node.js Buffer, combined with a function that would separate the string by two characters and adding a '0x' prefix.
Here are the two ways to do it.
// Solution 1 - direct string to buffer conversion
const hexToString = (hex) => {
let ar = [];
for (let c = 0; c < hex.length; c += 2) {
ar.push('0x' + hex.substr(c, 2));
}
return ar;
};
let s = "CA030101CF";
let buf = Buffer.from(hexToString(s));
console.log(buf);
// Solution 2 - string to buffer conversion
const hexToInt = (hex) => {
let ar = [];
for (let c = 0; c < hex.length; c += 2) {
ar.push(parseInt('0x' + hex.substr(c, 2), 16));
}
return ar;
};
let s = "CA030101CF";
let buf = Buffer.from(hexToInt(s));
console.log(buf);
I haven't checked yet which one is more efficient, but both solutions produce same result - a buffer of hexadecimal values <Buffer ca 03 01 01 cf>.