1

When I use packing in struct, I find out that during unpacking that I have extra characters after I unpack the byte object.

For example before packing: c = b'CONNECT' value gotten after unpacking using struct is b'CONNECT\x00\x00\x00\x00\x00'

Here is my code:

import struct
import datetime
import binascii

string_format = '12s'
s = struct.Struct(string_format)
str = 'CONNECT'
byte = str.encode()
print(byte)

packed_data = s.pack(byte)
print(packed_data)
unpacked_data = s.unpack(packed_data)
unpacked_data = unpacked_data[0]
arr = []

for item in unpacked_data.decode():
    print(item)
    arr.append(item)

print(arr)

How can I get b'CONNECT' after unpacking.

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
Francis
  • 61
  • 1
  • 4
  • Can you show us your code? – Sunny Patel Apr 20 '18 at 15:21
  • import struct import datetime import binascii string_format = '12s' s = struct.Struct(string_format) str = 'CONNECT' byte = str.encode() print(byte) packed_data = s.pack(byte) print(packed_data) unpacked_data = s.unpack(packed_data) unpacked_data = unpacked_data[0] arr = [] for item in unpacked_data.decode(): print(item) arr.append(item) print(arr) – Francis Apr 20 '18 at 15:41

1 Answers1

0

The additional NUL bytes are added because you update the struct format to have 12 characters with '12s'. If you add print('CONNECT'.encode()) before all your statements, you'll see that it's correct.

Since you'll probably want to strip off the additional characters, just use that function:

print(repr(unpacked_data.decode().strip()))          #Prints 'CONNECT'
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46