Concatenating multiple bytes-like Objects

Posted on
Mon Jun 06, 2022 7:02 pm
Ramias offline
Posts: 272
Joined: Nov 24, 2015

Concatenating multiple bytes-like Objects

I am hacking through the Samsung TV plugin (I am not the original author) to get it to work with Python 3. The code takes various valuues - Mac, IP etc; base64encodes each one and then in Python 2, concatenates those along with some other fields and sends via sockets as a single value.

Apparently in Python 2 you can concatenate bytes-like objects just like strings with the + sign.

How can I do that in Python 3?

In the below test code how do I correctly generate messagepart1 so it is a bytes-like object?


Code: Select all
import base64, socket
myip = "10.51.2.40"
mymac = "aa:bb:cc:dd:ee:ff"
appstring = "iphone..iapp.samsung"
remotename = "Indigo Remote"
tvip = "10.51.9.10"


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((tvip, 55000))

ipencoded = base64.b64encode(bytes(myip,'UTF-8'))
macencoded = base64.b64encode(bytes(mymac,'UTF-8'))
remotename = base64.b64encode(bytes(remotename,'UTF-8'))
appstring = base64.b64encode(bytes(appstring,'UTF-8'))

messagepart1 = chr(0x64) + chr(0x00) + chr(len(ipencoded)) \
+ chr(0x00) + ipencoded \
+ chr(len(macencoded)) \
+ chr(0x00) \
+ macencoded \
+ chr(len(remotename)) \
+ chr(0x00) \
+ remotename

part1 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \
+ chr(len(messagepart1)) + chr(0x00) + messagepart1

sock.send(part1)
messagepart2 = chr(0xc8) + chr(0x00)
part2 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \
+ chr(len(messagepart2)) + chr(0x00) + messagepart2
sock.send(part2)


Posted on
Mon Jun 06, 2022 8:06 pm
FlyingDiver offline
User avatar
Posts: 7221
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: Concatenating multiple bytes-like Objects

Your problem is that in Python3 the chr() function returns a unicode character.

You can use '+' to concatenate bytearray objects just like you would for strings. So you just need to make sure everything is a bytearray type.

Is that the original code? Because it would probably work to just keep all the string generation the same, and just convert from a string to a byte array just before you send it. Which would be:

Code: Select all
sock.send(part1.encode('utf-8')

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 1 guest