字数组转字符串 [英] Word Array to String
问题描述
如何在 Javascript 或 Jquery 中执行此操作?
how to do this in Javascript or Jquery?
请分两步提出建议:
1.- 字数组到单字节数组.
1.- Word Array to Single Byte Array.
2.- 字节数组到字符串.
2.- Byte Array to String.
也许这会有所帮助:
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
推荐答案
您要实现的目标已经在 CryptoJS 中实现.来自文档:
What you are trying to achieve is already implemented in CryptoJS. From the documentation:
您可以通过显式调用 toString 方法并传递编码器将 WordArray 对象转换为其他格式.
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
var hash = CryptoJS.SHA256("Message");
alert(hash.toString(CryptoJS.enc.Base64));
alert(hash.toString(CryptoJS.enc.Hex));
老实说,我不知道您为什么要自己实施……但是,如果您绝对需要在您提到的 2 个步骤中手动"执行此操作,则可以尝试以下操作:
Honestly I have no idea why you want to implement that yourself... But if you absolutely need to do it "manually" in the 2 steps you mentioned, you could try something like this:
function wordToByteArray(wordArray) {
var byteArray = [], word, i, j;
for (i = 0; i < wordArray.length; ++i) {
word = wordArray[i];
for (j = 3; j >= 0; --j) {
byteArray.push((word >> 8 * j) & 0xFF);
}
}
return byteArray;
}
function byteArrayToString(byteArray) {
var str = "", i;
for (i = 0; i < byteArray.length; ++i) {
str += escape(String.fromCharCode(byteArray[i]));
}
return str;
}
var hash = CryptoJS.SHA256("Message");
var byteArray = wordToByteArray(hash.words);
alert(byteArrayToString(byteArray));
wordToByteArray
函数应该可以完美运行,但要注意 byteArrayToString
几乎在任何情况下都会产生奇怪的结果.我对编码了解不多,但 ASCII 仅使用 7 位,因此在尝试对整个字节进行编码时不会得到 ASCII 字符.所以我添加了 escape
函数,至少能够显示你可能得到的所有那些奇怪的字符.;)
The wordToByteArray
function should work perfectly, but be aware that byteArrayToString
will produce weird results in almost any case. I don't know much about encodings, but ASCII only uses 7 bits so you won't get ASCII chars when trying to encode an entire byte. So I added the escape
function to at least be able to display all those strange chars you might get. ;)
我建议您使用 CryptoJS 已经实现的函数或仅使用字节数组(不将其转换为字符串)进行分析.
I'd recommend you use the functions CryptoJS has already implemented or just use the byte array (without converting it to string) for your analysis.
这篇关于字数组转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!