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?
asked Aug 4, 2012 at 14:26
user485498
1 Answer 1
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'
answered Aug 4, 2012 at 14:30
JBernardo
33.6k13 gold badges92 silver badges120 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
JBernardo
@JJG You store your bytes in strings or bytestrings (Py3k), right? So, if the result is printable, it'll will appear this way.
JBernardo
@JJG that's because you're using a number smaller than 83 and
chr can't handle negative numbersJBernardo
@JJG You can add 256 for negative numbers to wrap around
lang-py