使用JavaScript将十六进制的数字用于char



如何使用JavaScript将字符串"C3"转换为其字符?我尝试了charCodeAttoString(16)和所有内容,但它不起作用。

var justtesting = "C3"; // There's an input here
var tohexformat = 'x' + justtesting; // Gives the wrong hexadecimal number
var finalstring = tohexformat.toString(16);

您需要的只是parseInt和可能的String.fromCharCode

parseInt接受字符串和 radix ,又称您要转换的基础。

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);

另一种简单的方法是打印&quot&#&quot 这样的charcode:

for(var i=9984; i<=10175; i++){
    document.write(i + "&nbsp;&nbsp;&nbsp;" + i.toString(16) + "&nbsp;&nbsp;&nbsp;&#" + i + "<br>");
}

for(var i=0x2700; i<=0x27BF; i++){
    document.write(i + "&nbsp;&nbsp;&nbsp;" + i.toString(16) + "&nbsp;&nbsp;&nbsp;&#" + i + "<br>");
}

jsfiddle

最新更新