如何使用javascript将p.ex字符串“C3”转换为char?我试过charCodeAt,toString(16)和所有的东西,不起作用。
var justtesting= "C3"; //there's an input here
var tohexformat= '\x' + justtesting; //gives wrong hex number
var finalstring= tohexformat.toString(16);
谢谢
最佳答案
您只需要 parseInt
,也可以是 String.fromCharCode
。parseInt
接受一个字符串和一个基数,也就是您要从中转换的基数。
console.log(parseInt('F', 16));
String.fromCharCode
将获取一个字符代码并将其转换为匹配的字符串。console.log(String.fromCharCode(65));
因此,这是将
C3
转换为数字以及可选地转换为字符的方法。var input = 'C3';
var decimalValue = parseInt(input, 16); // Base 16 or hexadecimal
var character = String.fromCharCode(decimalValue);
console.log('Input:', input);
console.log('Decimal value:', decimalValue);
console.log('Character representation:', character);