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
CodePudding user response:
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))
CodePudding user response:
You can do something like this:
def int_to_bytes(i, length):
result = bytearray(length)
for index in range(length):
result[index] = i & 0xff
i >>= 8
return result
This code uses a for loop to iterate over the specified length. In each iteration, it uses the bitwise AND operator (&) to extract the least significant byte of the integer and store it in the result bytearray. It then uses the bitwise right shift operator (>>) to shift the integer to the right by 8 bits, discarding the least significant byte. This process is repeated until all bytes have been extracted from the integer and stored in the result bytearray. Finally, the result bytearray is returned.
Here is an example of how this code might work:
int_to_bytes(0x12345678, 4)
# returns bytearray(b'\x78\x56\x34\x12')
In this example, the int_to_bytes function is called with the integer 0x12345678 and a length of 4. This means that the integer will be converted to a 4-byte sequence, with the least significant byte first. The for loop iterates 4 times, and in each iteration it uses the bitwise AND and right shift operators to extract and discard each byte of the integer. At the end of the loop, the result bytearray contains the bytes [0x78, 0x56, 0x34, 0x12], which are the bytes of the original integer in little-endian order. The result bytearray is then returned.
CodePudding user response:
You can just use bytes() function