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]
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 )
Regards,
B.D.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.