Fix tests and packer (multi negative still broken)

This commit is contained in:
ChillerDragon 2022-11-06 16:24:47 +01:00
parent 01d8f8d8e6
commit cca183818e
2 changed files with 31 additions and 20 deletions

View file

@ -107,7 +107,7 @@ class Unpacker
bytes = @data.map { |byte| byte.to_s(2).rjust(8, '0') }
first = bytes[0]
sign = first[1] == '1' ? -1 : 1
sign = first[1]
bits = []
# extended
@ -127,7 +127,8 @@ class Unpacker
bits = [first[2..]]
@data = @data[1..]
end
bits.join.to_i(2) * sign
num = bits.join.to_i(2)
sign == '1' ? -(num + 1) : num
end
end

View file

@ -20,17 +20,27 @@ describe 'Unpacker', :unpacker do
end
it 'Should unpack negative integers' do
u = Unpacker.new([0x41, 0x42])
u = Unpacker.new([0x40, 0x41, 0x42])
# 0x40 => 1000 0000
# ^^ ^
# negative\ /
# \ /
# 0
#
# There is no -0 so it will be -1
expect(u.get_int).to eq(-1)
expect(u.get_int).to eq(-2)
expect(u.get_int).to eq(-3)
end
it 'Should unpack positive and negative integers' do
u = Unpacker.new([0x01, 0x02, 0x41, 0x42])
u = Unpacker.new([0x01, 0x02, 0x03, 0x40, 0x41, 0x42])
expect(u.get_int).to eq(1)
expect(u.get_int).to eq(2)
expect(u.get_int).to eq(3)
expect(u.get_int).to eq(-1)
expect(u.get_int).to eq(-2)
expect(u.get_int).to eq(-3)
end
it 'Should pack and unpack and match from 0 to 63' do
@ -57,23 +67,23 @@ describe 'Unpacker', :unpacker do
u = Unpacker.new(['00000011'.to_i(2)])
expect(u.get_int).to eq(3)
# u = Unpacker.new(['01000000'.to_i(2)])
# expect(u.get_int).to eq(-1)
u = Unpacker.new(['01000000'.to_i(2)])
expect(u.get_int).to eq(-1)
end
# it 'Should pack and unpack and match from -3 to 3' do
# (-3..3).each do |i|
# u = Unpacker.new(Packer.pack_int(i))
# expect(u.get_int()).to eq(i)
# end
# end
it 'Should pack and unpack and match from -3 to 3' do
(-3..3).each do |i|
u = Unpacker.new(Packer.pack_int(i))
expect(u.get_int()).to eq(i)
end
end
# it 'Should pack and unpack and match from -63 to 63' do
# (-63..63).each do |i|
# u = Unpacker.new(Packer.pack_int(i))
# expect(u.get_int()).to eq(i)
# end
# end
it 'Should pack and unpack and match from -63 to 63' do
(-63..63).each do |i|
u = Unpacker.new(Packer.pack_int(i))
expect(u.get_int()).to eq(i)
end
end
it 'Should unpack 0000 0001 to 1' do
u = Unpacker.new(['00000001'.to_i(2)])
@ -112,8 +122,8 @@ describe 'Unpacker', :unpacker do
expect(u.get_int).to eq(64)
end
it 'Should unpack 1100 0001 0000 0001 to -65' do
u = Unpacker.new(['11000001'.to_i(2), '00000001'.to_i(2)])
it 'Should unpack 1100 0000 0000 0001 to -65' do
u = Unpacker.new(['11000000'.to_i(2), '00000001'.to_i(2)])
expect(u.get_int).to eq(-65)
end
end