Convert raw string to array of big words with Ruby
I would like to convert a raw string to an array of big words.
As an example, here's a JavaScript function that does it well (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 could be String # unpack (format) .
However, I don't know what the correct format should be.
Thanks for any help.
Hello
+2
a source to share
1 answer
I think you should have posted some examples of I / O pairs. Here's the 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'm not sure if it will give the same results, if you try it on multiple multibyte characters, unpack
shouldn't ignore anything.
+2
a source to share