Skip to content

Commit eac22b2

Browse files
committed
Change the order of bits based on how Redis setbit/getbit stores them
1 parent 6018faa commit eac22b2

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

lib/bitarray.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@ def initialize(size, field = nil)
1313
# Set a bit (1/0)
1414
def []=(position, value)
1515
if value == 1
16-
@field.setbyte(position >> 3, @field.getbyte(position >> 3) | (1 << (position % 8)))
16+
@field.setbyte(position >> 3, @field.getbyte(position >> 3) | (1 << (7 - position % 8)))
1717
else
18-
@field.setbyte(position >> 3, @field.getbyte(position >> 3) ^ (1 << (position % 8)))
18+
@field.setbyte(position >> 3, @field.getbyte(position >> 3) ^ (1 << (7 - position % 8)))
1919
end
2020
end
2121

2222
# Read a bit (1/0)
2323
def [](position)
24-
(@field.getbyte(position >> 3) & (1 << (position % 8))) > 0 ? 1 : 0
24+
(@field.getbyte(position >> 3) & (1 << (7 - position % 8))) > 0 ? 1 : 0
2525
end
2626

2727
# Iterate over each bit
@@ -31,7 +31,7 @@ def each(&block)
3131

3232
# Returns the field as a string like "0101010100111100," etc.
3333
def to_s
34-
@field.bytes.collect{|ea| ("%08b" % ea).reverse}.join[0, @size]
34+
@field.bytes.collect { |ea| ("%08b" % ea) }.join[0, @size]
3535
end
3636

3737
# Returns the total number of bits that are set

test/test_bitarray.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ def test_to_s
5252
assert_equal "01000111001000001000000000000000010", ba.to_s
5353
end
5454

55+
def test_field
56+
ba = BitArray.new(35)
57+
[1, 5, 6, 7, 10, 16, 33].each{|i|ba[i] = 1}
58+
assert_equal "0100011100100000100000000000000001000000", ba.field.unpack('B*')[0]
59+
end
60+
5561
def test_total_set
5662
ba = BitArray.new(10)
5763
ba[1] = 1

0 commit comments

Comments
 (0)