eblot / pyftdi

FTDI device driver written in pure Python
Other
509 stars 212 forks source link

BitSequence Bug by using bits with padded zeros #317

Open bauergeorg opened 2 years ago

bauergeorg commented 2 years ago

Hi I found the following bug:

from pyftdi.bits import BitSequence

value1 = '002' # hex
length = 3*4

print(value1)
int1 = int(value1,16)
print(int1)
bin1 = bin(int1)
print(bin1)
print(bin1[2:])
ans1 = BitSequence(bin1[2:], msb=True, length=length)
print(ans1)

value2 = '200' # hex
length = 3*4

print(value2)
int2 = int(value2,16)
print(int2)
bin2 = bin(int2)
print(bin2)
print(bin2[2:])
ans2 = BitSequence(bin2[2:], msb=True, length=length)
print(ans2)

The output is a litte bit confusing...

002
2
0b10
10
12: 1000 00000000
200
512
0b1000000000
1000000000
12: 1000 00000000

I think this is the same issue like: https://github.com/eblot/pyftdi/issues/245

bauergeorg commented 2 years ago

I found a solution to convert a hex value into a binary with padded zeros:

def hex_to_bits(value:str, length=None, padded_zeros=True) -> str:
    if length == None:
        length = len(value)*4
    ret = bin(int(value,16))[2:]
    if padded_zeros == True:
        ret = ret.rjust(length, '0')
    return ret