0

This one is driving me crazy:

I defined these two functions to convert between bytes and int resp. bytes and bits:

def bytes2int(bytes) : return int(bytes.encode('hex'), 16)

def bytes2bits(bytes) : # returns the bits as a 8-zerofilled string
    return ''.join('{0:08b}'.format(bytes2int(i)) for i in bytes)

This works as expected:

>>> bytes2bits('\x06')
'00000110'

Now I'm reading in a binary file (with a well defined data structure) and printing out some values, which works too. Here is an example:

The piece of code which reads the bytes from the file:

dataItems = f.read(dataSize)
for i in range(10) : // now only the first 10 items
    dataItemBits = bytes2bits(dataItems[i*6:(i+1)*6]) // each item is 6 bytes long
    dataType = dataItemBits[:3]
    deviceID = dataItemBits[3:8]
    # and here printing out the strings...
    # ...
    print("   => data type: %8s" % (dataType))
    print("   => device ID: %8s" % (deviceID))
    # ...

with this output:

-----------------------
Item #9: 011000010000000000111110100101011111111111111111
    97   bits: 01100001
     0   bits: 00000000
    62   bits: 00111110
   149   bits: 10010101
   255   bits: 11111111
   255   bits: 11111111

 =>  data type:      011  // first 3 bits
 =>  device ID:    00001  // next 5 bits

My problem is, that I'm unable to convert the 'bit-strings' to decimal numbers; if I try to print this

print int(deviceID, 2)

it gives me an the ValueError

ValueError: invalid literal for int() with base 2: ''

although deviceID is definitely a string (I'm using it before as string and printing it out) '00001', so it's not ''.

I also checked deviceID and dataType with __doc__ and they are strings.

This one works well in the console:

>>> int('000010', 2)
2
>>> int('000110', 2)
6

What is going on here?

UPDATE:

This is really weird: when I wrap it in a try/except block, it prints out the correct value.

try :
    print int(pmtNumber, 2) // prints the correct value
except :
    print "ERROR!" // no exception, so this is never printed

Any ideas?

tamasgal
  • 24,826
  • 18
  • 96
  • 135
  • Note that `ord()` turns a byte to an int much more efficiently. – Martijn Pieters May 06 '13 at 16:35
  • 1
    The error message is telling you what's wrong: you're passing an empty string. Your question shouldn't be "why can't `int()` parse a perfectly cromulent binary integer?", because `int()` can obviously do that; it should be "why is `deviceID` getting set to an empty string by the time I print it?" – kindall May 06 '13 at 16:36
  • @MartijnPieters I know, but only on characters, not on strings. I thought .encode is OK for a string… – tamasgal May 06 '13 at 16:37
  • @septi: Ah, yes, in which case you really want to use the `struct` module instead. :-) – Martijn Pieters May 06 '13 at 16:38
  • @MartijnPieters I will have look at it, thanks! – tamasgal May 06 '13 at 16:39

0 Answers0