使用Javascript来字符化十六进制数

问题描述 投票:0回答:2

如何使用 JavaScript 将字符串

"C3"
转换为其字符?我已经尝试过
charCodeAt
toString(16)
等等,但它不起作用。

var justtesting = "C3"; // There's an input here
var tohexformat = '\x' + justtesting; // Gives the wrong hexadecimal number

var finalstring = tohexformat.toString(16); 
javascript hex
2个回答
22
投票

您所需要的只是

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


0
投票

另一种简单的方法是像这样打印“&#”+ 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

© www.soinside.com 2019 - 2024. All rights reserved.