Reputation: 6231
I would like to convert a raw string to an array of big-endian words.
As example, here is a JavaScript function that do it well (by Paul Johnston):
/*
* Convert a raw string to an array of big-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binb(input)
{
var output = Array(input.length >> 2);
for(var i = 0; i < output.length; i++)
output[i] = 0;
for(var i = 0; i < input.length * 8; i += 8)
output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
return output;
}
I believe the Ruby equivalent can be String#unpack(format).
However, I don't know what should be the correct format parameter.
Thank you for any help.
Regards
Upvotes: 2
Views: 1279
Reputation: 44110
I think you should have posted few examples of the input/output pairs. Here's code that gives me the same output as your JS code in Chrome:
/* JS in Chrome: */
rstr2binb('hello world!')
[1751477356, 1864398703, 1919706145]
# irb, Ruby 1.9.1:
'hello world!'.unpack('N*')
#=> [1751477356, 1864398703, 1919706145]
However, I am not sure it will give the same results if you try it on some multibyte characters, unpack
shouldn't be ignoring anything.
Upvotes: 2