十六进制数使用JavaScript转换为字符

12
如何使用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);

你还没有在 C3 周围加上引号,所以它不会将其解释为字符串。 - Iluvatar
是的,我会。已编辑 :) - i.Dio
OP并没有试图将十进制值转换为十六进制。 - Mike Cluck
是的,它是一个字符串。我只是无法将字符串转换为十六进制,例如将31转换为数字1,因为当我尝试添加\x时,它只会给我两个额外的字符,而不是一个十六进制值。 - i.Dio
对于"C3",所需的输出是什么?是字符串"193"吗? - Peter Mortensen
2个回答

22

你只需要使用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);


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


这是一个虚假的回答吗?9984和10175是什么魔法数字?意图是什么? - Peter Mortensen
@PeterMortensen “魔法数字”只是utf-8字符的十进制表示。这是为了演示如何使用JavaScript将十六进制/十进制数字转换为字符的简单示例。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接