Search code examples
pythonhextornadoassert

Assert fails in Python


I have this code:

/server/frontend/wsn.py
Line 866:        
    netid = hextransform(int(nid), 16)

Line 156: 
    def hextransform(data, length):
        data = hex(data)[2:]
        assert(len(data) <= length)
        # zero-padding
        data = ('0' * (length - len(data))) + data
        # Swap 'bytes' in the network ID
        data = list(data)
        for i in range(0, length, 2):
            tmp = data[i]
            data[i] = data[i + 1]
            data[i + 1] = tmp
        # Reverse the whole string (TODO: CHECK) 
        data.reverse()
        #data = "".join(data)
        return data

My problem is when I have a nid = 15579202759033880576 for example. Is it too long?

The error I receive from Tornado is this:

Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 1739, in wrapper
    return method(self, *args, **kwargs)
  File "./wsn.py", line 866, in get
    netid = hextransform(int(nid), 16)
  File "./wsn.py", line 158, in hextransform
    assert(len(data) <= length)
AssertionError

But netid in hex is 0xd834725e00000000 and len(nid) = 16.

I don't know what the problem is.


Solution

  • The 'L' from the hex(int(num)) is your problem:

    >>> hex(int(15579202759033880576))[2:]
    'd834725e00000000L'   <-- 17 with the L
    

    The quickest fix for this is just to update your substring chop to get rid of that L as well:

    data = hex(data)[2:].split('L')[0]
    

    This will split your string around the L (if present) and give you the hex part. It's safe since 'L' isn't a hex character so it will only show up if you have a long string.