Blixt
Blixt

Reputation: 50179

How can I perform arithmetics on bytes in Python 2.x?

Given any number of bytes (as a binary string), what is the best way to add or substract a number to/from the set of bytes and get back the new set of bytes?

Example (I'm looking for a good implementation of add):

>>> add('\xFF' * 10, 1)
'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

(Given 10 bytes with a value of 255, adding one would give you back 11 bytes where the first one has value 1 and the rest value 0)

Upvotes: 0

Views: 2617

Answers (2)

Blixt
Blixt

Reputation: 50179

Here's the simplest solution I can think of. I'm hoping there's a nicer way though:

def add(bytes, value):
  x = '%x' % (long(bytes.encode('hex'), 16) + value)
  return ('0' + x if len(x) & 1 else x).decode('hex')

Upvotes: 1

Peter
Peter

Reputation: 553

Python can do arbitrary length integer math

>>> a = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
>>> print hex( a+1 )
0x10000000000000000000000000000000000000000000000000000000000000000L
>>> b = (1 << 8*32) -1
>>> print hex(b)
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffL

Upvotes: 0

Related Questions