0

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

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

3 Comments

sorry no libraries. just bitwise operations
what if i want big endian?
You reverse the output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.