Javascript 字数组转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11889329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Word Array to String
提问by Hymantrades
how to do this in Javascript or Jquery?
如何在 Javascript 或 Jquery 中执行此操作?
Please suggest in 2 steps:
请分两步建议:
1.- Word Array to Single Byte Array.
1.- 字数组到单字节数组。
2.- Byte Array to String.
2.- 字节数组到字符串。
Maybe this can help:
也许这可以帮助:
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;
}
回答by Aletheios
What you are trying to achieve is already implemented in CryptoJS. From the documentation:
您要实现的目标已经在 CryptoJS 中实现。从文档:
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
您可以通过显式调用 toString 方法并传递编码器将 WordArray 对象转换为其他格式。
var hash = CryptoJS.SHA256("Message");
alert(hash.toString(CryptoJS.enc.Base64));
alert(hash.toString(CryptoJS.enc.Hex));
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));
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. ;)
该wordToByteArray
函数应该可以完美运行,但请注意,byteArrayToString
几乎在任何情况下都会产生奇怪的结果。我对编码了解不多,但 ASCII 仅使用 7 位,因此在尝试对整个字节进行编码时不会得到 ASCII 字符。所以我添加了这个escape
函数,至少能够显示你可能得到的所有那些奇怪的字符。;)
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.
我建议您使用 CryptoJS 已经实现的函数,或者只使用字节数组(不将其转换为字符串)进行分析。