javascript中的字符到十六进制
谁能指导我如何在javascript中将char转换为十六进制?
例如:
Could anyone guide me on how to convert char to hex in javascript?
For example:
"入力されたデータは范囲外です."
到
"u5165u529Bu3055u308Cu305Fu30C7u30FCu30BFu306Fu7BC4u56F2u5916u3067u3059u3002"
"入力されたデータは範囲外です。"
to
"u5165u529Bu3055u308Cu305Fu30C7u30FCu30BFu306Fu7BC4u56F2u5916u3067u3059u3002"
这个网站做到了
但是我想不通.
任何建议.
谢谢,萨博坦
推荐答案
您可以遍历字符并使用 charCodeAt
函数获取它们的 UTF-16 值,然后用它们构造一个字符串.
You can loop through the characters and use the charCodeAt
function to get their UTF-16 values, then constructing a string with them.
这是我构建的一些代码,它比您链接的网站上的代码要好得多,并且应该更容易理解:
Here's some code I constructed that is much better than the code on the site you've linked, and should be easier to understand:
function string_as_unicode_escape(input) {
function pad_four(input) {
var l = input.length;
if (l == 0) return '0000';
if (l == 1) return '000' + input;
if (l == 2) return '00' + input;
if (l == 3) return '0' + input;
return input;
}
var output = '';
for (var i = 0, l = input.length; i < l; i++)
output += '\u' + pad_four(input.charCodeAt(i).toString(16));
return output;
}
让我们分解一下.
string_as_unicode_escape
采用一个参数,input
,它是一个字符串.pad_four
是一个做一件事的内部函数;它用前导'0'
字符填充字符串,直到长度至少为四个字符.- 首先将
output
定义为空字符串. - 对于字符串中的每个字符,将
u
附加到output
字符串.用input.charCodeAt(i)
取字符的 UTF-16 值,然后用.toString(16)
将其转换为十六进制字符串,然后用前导填充零,然后将结果附加到output
字符串. - 返回
输出
字符串.
string_as_unicode_escape
takes one argument,input
, which is a string.pad_four
is an internal function that does one thing; it pads strings with leading'0'
characters until the length is at least four characters long.- Start off by defining
output
as an empty string. - For each character in the string, append
u
to theoutput
string. Take the UTF-16 value of the character withinput.charCodeAt(i)
, then convert it to a hexadecimal string with.toString(16)
, then pad it with leading zeros, then append the result to theoutput
string. - Return the
output
string.
正如 Tim Down 所说,我们还可以将 0x10000
添加到 charCodeAt
值,然后添加 .slice(1)
调用产生的字符串.toString(16)
,实现填充效果.
As Tim Down commented, we can also add 0x10000
to the charCodeAt
value and then .slice(1)
the string resulting from calling .toString(16)
, to achieve the padding effect.
相关文章