import struct def int_to_bytes(value, size, big_endian=False): bs = [] for i in range(size): offset = i * 8 b = chr((value & (0xff << offset)) >> offset) if big_endian: bs.insert(0, b) else: bs.append(b) return b''.join(bs) def int32_to_bytes(value, big_endian=False): return int_to_bytes(value, 4, big_endian) def int64_to_bytes(value, big_endian=False): return int_to_bytes(value, 8, big_endian) if __name__ == '__main__': # the two commands below do the same print(repr(int64_to_bytes(65536, big_endian=True))) print(repr(struct.pack('>Q', 65536)))
see also
- Python: struct.pack
No comments:
Post a Comment