3

I have a integer. Lets say,

var = 83 #less than 0xff

And I have a byte. So let's say I have byte b and I want to calculate the integer value of

 b-=var #b as an integer value , possibly by eval(b)?

And then I want to turn it back into a byte, how can I do this in python?

1 Answer 1

3

If I understood the question, you can do:

>>> chr(ord('x') - 83)
'%'

where 'x' is your byte.

If you're on Python 3.x

>>> bytes([ord(b'x') - 83])
b'%'

Note ord(b'x') is the same as b'x'[0]

Another example (where the resulting byte is not printable and is shown in the \x00 form):

>>> chr(ord('\x53') - 83)
'\x00'
Sign up to request clarification or add additional context in comments.

5 Comments

@JJG You store your bytes in strings or bytestrings (Py3k), right? So, if the result is printable, it'll will appear this way.
OK. Well, I'm getting an error: ValueError: chr() arg not in range(256) . I don't know why this is happening. Also I'm using Pytohn 2.7
@JJG that's because you're using a number smaller than 83 and chr can't handle negative numbers
@JJG You can add 256 for negative numbers to wrap around
Thanks all! I think I did it. I did the +=256 wrap around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.