Created
October 7, 2010 22:09
-
-
Save sandrods/616002 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class BitArray | |
| attr_accessor :array | |
| def initialize(value = nil) | |
| if value | |
| @array = value.to_s(2).split('').map {|i| i.to_i} | |
| else | |
| @array = [] | |
| end | |
| end | |
| def on(position) | |
| raise 'BitArray is 1 based' if position == 0 | |
| @array[position] = 1 | |
| update_nils | |
| end | |
| def on?(position) | |
| @array[position] == 1 | |
| end | |
| def off(position) | |
| raise 'BitArray is 1 based' if position == 0 | |
| @array[position] = 0 | |
| update_nils | |
| end | |
| def off?(position) | |
| @array[position] == 0 || @array[position].nil? | |
| end | |
| def to_i | |
| @array[0] = 1 | |
| @array.join.to_i(2) | |
| end | |
| private | |
| def update_nils | |
| @array.map! {|a| a.nil? ? 0 : a} | |
| end | |
| end | |
| a = BitArray.new | |
| a.on(3) | |
| a.on(2) | |
| puts a.on?(3) | |
| puts a.on?(2) | |
| puts a.on?(1) | |
| puts "val" | |
| puts a.to_i | |
| i = a.to_i | |
| b = BitArray.new(i) | |
| puts b.array.join | |
| puts b.on(1) | |
| puts b.on?(3) | |
| puts b.on?(2) | |
| puts b.on?(1) | |
| puts b.array[3] | |
| puts b.array[2] | |
| puts b.array[1] | |
| puts "val" | |
| puts b.to_i |
Author
Author
Na verdade dá. Fiz com que ela seja 1 based. Assim uso a posicao Zero sempre com um, fazendo com que os zeros sejam sempre significativos
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Não dá pra serializar um bitarray se não souber de antemão o número de posições do array.