pack.py 1004 B

123456789101112131415161718192021222324252627
  1. import struct
  2. # Test strings and fixed-length strings
  3. assert struct.pack('5s', b'Hello') == b'Hello'
  4. assert struct.pack('10s', b'World') == b'World\x00\x00\x00\x00\x00'
  5. assert struct.pack(
  6. 'hhl', 1, 2, 3) == b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
  7. # Test signed short, unsigned short, and signed long
  8. assert struct.pack(
  9. 'hHl', -1, 255, 1234567890) == b'\xff\xff\xff\x00\x00\x00\x00\x00\xd2\x02\x96I\x00\x00\x00\x00'
  10. # Test single precision float and double precision float
  11. assert struct.pack(
  12. 'fd', 3.14159, 123.45678901234567) == b'\xd0\x0fI@\x00\x00\x00\x00\x98L\xfb\x07<\xdd^@'
  13. # Test byte order and alignment
  14. assert struct.pack('>ih5s', 256, 6553,
  15. b'Python') == b'\x00\x00\x01\x00\x19\x99Pytho'
  16. # Test combination of multiple values
  17. #! NOT SUPPORTED
  18. # assert struct.pack('chHiIq', b'A', 127, 3268, 2147, 42945, 9220) == \
  19. # b'A\x00\x7f\x00\xc4\x0c\x00\x00c\x08\x00\x00\xc1\xa7\x00\x00\x04$\x00\x00\x00\x00\x00\x00'
  20. print('PASS')