views:

317

answers:

2

I need to convert an array of integers to a little endian bitmask using Ruby. Any links or hints would be appreciated.

the example says [2,7,9,11] => "4205"

a = [2,7,9,11] # 4205
b = [1,2,3,4] # 0F00
def array_to_mask(arr)
  mask = 0
  arr.each do |i|
    mask = mask | (1 << i)
  end
  return mask.to_s(16)
end
p array_to_mask(a) # a84
p array_to_mask(b) # 1e

This does not work, but am i on the right track?

+2  A: 

Can't you use arr.pack()? It has options for byte order.

Update: Ok I've taken a look at the documentation you mentioned and the only way I can make the example work is this:

  7          2              11   9      (decimal index count)
0 1 0 0  0 0 1 0  0 0 0 0  0 1 0 1      (bits)

   4        2        0        5         (nibbles, in hex)

But that would mean that would mean that the 4205 are 4 nibbles that together represent 2 bytes? That is the only way I could make the first byte have the second and seventh bit set (reading little endian).

... This is more of an 'understanding the docs' issue than it it a ruby issue.

So the array solution is not the one you need, because you need to set the individual bits in a number. This is best achieved using (left) bit shift << and or'ing | the results together.

Simon Groenewolt
I probably can, I didn't think it would be that easy. I'm testing directives to see which I need now
Jeff Rossi
Can this be done in a function?
Jeff Rossi
A: 

Enfora sent me a calculator which I examined to write a function. Hopefully this explanation will help whoever is next to try this.

values: [2,7,9,11]
Bits:   | 8 7 6 5 | 4 3 2 1 | 16 15 14 13 | 12 11 10 9 |
Binary: | 0 1 0 0 | 0 0 1 0 | 0  0  0  0  | 0  1  0  1 |
Hex:    |    4    |    2    |      0      |      5     |  
Jeff Rossi