0

In Python 2:

import struct
struct.pack('B', 21)[0] # returns '\x15'

In Python 3:

import struct
struct.pack('B', 21)[0] # returns 21

Is there some way to create the byte string returned by Python 2 in Python 3? Any pointers would be greatly appreciated!

asked May 30, 2020 at 18:42
6
  • Ooh, chr(21)! Commented May 30, 2020 at 18:44
  • 1
    This is an interesting question. In python 2, pack returns a string and each member of a string is a single character string. In python 3, pack quite sensibly returns a bytes array but individual members of a bytes array are ints < 256. Its a place where 2 to 3 conversion could break. By "member", I mean the value you get when you index an item. Commented May 30, 2020 at 18:55
  • Ya, I'm trying to convert a Python implementation of the original NES synthesizer (written in machine code) to Python 3 and there are lots of breaking changes in the handling of binary objects between Python 2 and 3! Commented May 30, 2020 at 18:58
  • At the python level, the result of pack is an opaque blob. You get the right stuff back when you unpack. When I wrote my comment I wasn't sure the use case of python ever touching a member of the blob. I'm still not sure I've got one. Commented May 30, 2020 at 19:02
  • 1
    It would bite you if you want to send data a byte at a time. for b in data:myconnection.send(b). Commented May 30, 2020 at 19:13

1 Answer 1

2

Just don't index the byte string it returns:

>>> struct.pack('B', 21)
b'\x15'
answered May 30, 2020 at 18:45
Sign up to request clarification or add additional context in comments.

9 Comments

@duhaime That's what you wrote, the first byte is 21. Clearly you are looking for something else.
@duhaime Are you looking for hex(21) or "{:x}".format(21)?
@duhaime Getting the hexadecimal representation of an integer as a string is a way different question that you originally asked though.
I cleaned up some of my comments but wanted to ask--this is a bytes data type, whereas Python 2 returns a string--can one get this object as a string type in Python 3? chr(21) returns the string that's needed
@duhaime That is not a valid string for all values you can give to the struct.pack. You will have to change the other code to work with bytes instead of strings.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.