bit_length returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros. So
(x.bit_length() + 7) // 8
will just give you the number of bytes necessary to represent that integer x. You could also write something like
from math import ceil
ceil(x.bit_length() / 8)
to get the same number.
The method to_bytes() requires this byte length as its first argument.
To account for x == 0, use the max function to ensure that the number of bytes is at least one:
x.to_bytes(length=(max(x.bit_length(), 1) + 7) // 8, byteorder='little')
Answer from S F on Stack OverflowHow do I convert a string to bytes?
python - Convert byte string to bytes or bytearray - Stack Overflow
python - About to_bytes() method of int type - Stack Overflow
Converting integer to byte string problem in python 3
Suppose I something like
s = "GW\x25\001"
How do I convert that string to bytes, interpreting the backslashes as escapes? In other words, the resulting byte array should be of length 4.
UPDATE: Hmmm, I was taking the string from sys.argv[1], which seems to complicate things and not make it turn out as expected. So I'm still not sure what the answer is.
in python 3:
>>> a=b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>> b = list(a)
>>> b
[0, 0, 0, 0, 7, 128, 0, 3]
>>> c = bytes(b)
>>> c
b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>>
From string to array of bytes:
a = bytearray.fromhex('00 00 00 00 07 80 00 03')
or
a = bytearray(b'\x00\x00\x00\x00\x07\x80\x00\x03')
and back to string:
key = ''.join(chr(x) for x in a)
Hi there. If I want to replicate pythons code like (3).to_bytes(20, "big"), how would I do it? If 20 was 32 I could do this:
buf := bytes.Buffer{} err := binary.Write(buf, binary.BigEndian, int32(3)) if err != nil { return nil, err } return but.Bytes()
But how do I do it with an int20 being the required type
Decode the bytes object to produce a string:
>>> b"abcde".decode("utf-8")
'abcde'
The above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!
Decode the byte string and turn it in to a character (Unicode) string.
Python 3:
encoding = 'utf-8'
b'hello'.decode(encoding)
or
str(b'hello', encoding)
Python 2:
encoding = 'utf-8'
'hello'.decode(encoding)
or
unicode('hello', encoding)