Array conversion

Hi,

I have a array of 32 bits digests such as this one:

array = [1717922406, 543519338, 543585641, 1701343776, 1718969704,
544368245, 1751457906, 1713399157]

And I would like to convert it into another array of 128 bits digests.

According so test, I think the such array is:
[136107835579490162288229994478942319136,
136190811075650685875822190301307495797]

Do you know if there is a simple way to do a such array conversion.

Thank you all.

Regards

On 16.05.2010 23:58, Paul A. wrote:

Do you know if there is a simple way to do a such array conversion.

Group the array into slices of 4 and then “concatenate” each slice
by shifting and adding:

array.each_slice(4).map do |slice|
slice.inject(0) do |sum,ele|
(sum<<32) + ele
end
end
#=> [136107835579490162288229994478942319136,
136190811075650685875822190301307495797]

Sebastian H. wrote:

On 16.05.2010 23:58, Paul A. wrote:

Do you know if there is a simple way to do a such array conversion.

Group the array into slices of 4 and then “concatenate” each slice
by shifting and adding:

Awesome! Many thanks, Sebastian!

Just a last question: how can we do the oposite operation?

Hi,
On 17 May 2010 00:51, Paul A. [email protected] wrote:

Just a last question: how can we do the oposite operation?

I suppose this is a way:

array_32bit = [1717922406, 543519338, 543585641, 1701343776,
1718969704, 544368245, 1751457906, 1713399157]
array_128bit = [136107835579490162288229994478942319136,
136190811075650685875822190301307495797]

class Array
def convert_digest(from_bits, to_bits)
if from_bits < to_bits
self.each_slice(to_bits/from_bits).map do |slice|
slice.inject(0) do |sum,hash|
(sum<<from_bits) + hash
end
end
else
self.inject([]) { |result, hash|
result + (from_bits/to_bits).times.inject([]) { |ary|
hash, rest = hash.divmod(2**to_bits)
ary << rest
}.reverse
}
end
end
end

p array_32bit.convert_digest(32,128) == array_128bit
p array_128bit.convert_digest(128,32) == array_32bit
p array_32bit.convert_digest(32,128).convert_digest(128,32) ==
array_32bit
p array_128bit.convert_digest(128,32).convert_digest(32,128) ==
array_128bit

(always be careful with Integer#<<(n), as it can easily ‘steal’ all
your memory if you are a bit heavy on the n :wink: )

Regards,
B.D.