2

I have this:

>>> a1 = pack('>L', 18)
>>> a1
b'\x00\x00\x00\x12'

And:

>>> a2 = [int(0x0), int(0x0), int(0x0), int(0x12)]
>>> a2
[0, 0, 0, 18]

Why aren't they equal?

>>> a1 == a2
False
Ko32mo
  • 107
  • 8

3 Answers3

1

Because you have to transform the second variable a2 in a byte string if you want to be equals, a1 is a list of ints, and a2 is a byte string, so they will never be equeal unless you transform a2, for example:

import struct
import array

a1 = struct.pack('>L', 18)
print(a1)
$b'\x00\x00\x00\x12'

a2 = [int(0x0), int(0x0), int(0x0), int(0x12)]
print(a2)
$[0, 0, 0, 18] #this is a list

print(a1 == a2)
$False

a3 = array.array('B',a2).tostring() #transform the list into byte
print(a3)
$b'\x00\x00\x00\x12' 

print(a1 == a3)
$True
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • `#transform the list into byte` --> what's the byte here? – Ko32mo Jun 11 '17 at 04:59
  • @Ko32mo b'\x00\x00\x00\x12' this is a byte string, see this post https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal – developer_hatch Jun 11 '17 at 05:01
  • @Ko32mo don't forget it is a good practice to accept (only one) answer (by click the check box in the left top of the answer) if the answer was helpul :), also don't forget to vote if you found the answer useful – developer_hatch Jun 11 '17 at 05:02
  • @Ko32mo also check this link if you feel a little loss https://stackoverflow.com/questions/6224052/what-is-the-difference-between-a-string-and-a-byte-string – developer_hatch Jun 11 '17 at 05:03
0

pack('>L', 18) returns a byte object and a2 is a list.

jacoblaw
  • 1,263
  • 9
  • 9
0

A list and a byte string aren't equivalent types, even though they're similar. To convert your list to a byte string, you can use the following methods depending on whether you're using Python 2 or 3.

Python 2:

>>> ''.join(chr(c) for c in a2)
'\x00\x00\x00\x12'

Python 3:

>>> bytes(a2)
b'\x00\x00\x00\x12'
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    what's a byte string? what's a real world example? does byte string exist in other programming languages? – Ko32mo Jun 11 '17 at 04:58