I have 2 inputs: i (the integer), length (how many bytes the integer should be encoded).
how can I convert integer to bytes only with bitwise operations.
def int_to_bytes(i, length):
for _ in range(length):
pass
Without libraries (as specified in the original post), use int.to_bytes.
>>> (1234).to_bytes(16, "little")
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
IOW, your function would be
def int_to_bytes(i, length):
return i.to_bytes(length, "little")
(or big, if you want big-endian order).
With just bitwise operations,
def int_to_bytes(i, length):
buf = bytearray(length)
for j in range(length):
buf[j] = i & 0xFF
i >>= 8
return bytes(buf)
print(int_to_bytes(1234, 4))