String.fromCharCode(72) 给出 H。如何从 char H 中获取数字 72?
6 回答
'H'.charCodeAt(0)
使用 charCodeAt:
var str = 'H';
var charcode = str.charCodeAt(0);
@Silvio 的答案仅适用于高达 0xFFFF 的代码点(这最终是 String.fromCharCode 可以输出的最大值)。你不能总是假设一个字符的长度是一:
''.length
-> 2
这是可行的:
var utf16ToDig = function(s) {
var length = s.length;
var index = -1;
var result = "";
var hex;
while (++index < length) {
hex = s.charCodeAt(index).toString(16).toUpperCase();
result += ('0000' + hex).slice(-4);
}
return parseInt(result, 16);
}
使用它:
utf16ToDig('').toString(16)
-> "d800df30"
您可以像这样定义自己的全局函数:
function CHR(ord)
{
return String.fromCharCode(ord);
}
function ORD(chr)
{
return chr.charCodeAt(0);
}
然后像这样使用它们:
var mySTR = CHR(72);
或者
var myNUM = ORD('H');
(如果您想多次使用它们,和/或在代码中多次使用它们。)
String.fromCharCode
接受多个参数,所以这是有效的:
const binaryArray = [10, 24] // ...
str = String.fromCharCode(...binaryArray)
如果您正在寻找相反的东西(就像我一样),这可能会派上用场:
const binaryArray = str
.split('')
.reduce((acc, next) =>
[...acc, next.charCodeAt(0)],
[]
)
如果必须考虑编码,请注意charCodeAt
来自String
object 的方法将默认为 utf16 编码。您可以使用Node.jsstring_decoder
对象的对象和 encoding 参数来应用特定的编码。 Buffer
charCodeAt
即使使用 utf-8 编码String
对象,该方法也仅提供 ascii/utf-16 编码:
str=new String(new Buffer([195,169]))
// -> [String: 'é']
str.charCodeAt(0)
// -> 233
使用UTF-16构建字符串fromCharCode
是不正确的:
myStr=String.fromCharCode(50089, 65, 233)
// -> '쎩Aé'
Buffer.from(myStr, 'utf-8')
// -> <Buffer ec 8e a9 41 c3 a9>
Buffer.from(myStr, 'ascii')
// -> <Buffer a9 41 e9>
myStr.charCodeAt(0)
// -> 50089
myStr.charCodeAt(2)
// -> 233
这是一个编码和解码 UTF8 字节和 ASCII 字节的简单示例:
var dec=new string_decoder.StringDecoder('utf-8');
dec.write(Buffer.from([65,67,195,169,98]));
// -> 'ACéb'
var theBytes=new Buffer('aéé','utf-8');
// -> <Buffer 61 c3 a9 c3 a9>
var dec=new string_decoder.StringDecoder('ascii')
dec.write(Buffer.from([65,67,195,169,98]))
// -> 'ACC)b'
var theBytes=new Buffer('aéé','ascii')
// -> <Buffer 61 e9 e9>
该StringDecoder.write
方法将从String
提供的字节缓冲区返回一个对象。
对象的 encoding 参数Buffer
为您提供了一种Buffer
从提供的 String 中获取带有编码字节的对象提要的方法。
所以要获得 char 'H' 的 ASCII 编码:
new Buffer('H','ascii');
// -> <Buffer 48>
new Buffer('H','ascii')[0];
// -> 72
这样,您还可以像这样处理多字节编码的字符:
new Buffer('é','ascii');
// -> <Buffer e9>
arr=new Buffer('é','ascii');
// -> <Buffer e9>
code=arr.readUIntBE(0,arr.length);
// -> 233
code.toString(16);
// -> 'e9'
new Buffer('é','utf-8');
// -> <Buffer c3 a9>
arr=new Buffer('é','utf-8');
// -> <Buffer c3 a9>
code=arr.readUIntBE(0,arr.length);
// -> 50089
code.toString(16)
// -> 'c3a9'