olyboy16
olyboy16

Reputation: 66

How can I write raw byte characters in Python string?

I am to develop an app that sends raw binary data over a socket network.

I have been given the characters to be

0x53 0x69 0x75 0x64 0x69 0x5F 0x37 0x42 0x6D 0x00 0x04 0x00 0x01 0x00 0x01 0x00 0x00 0x00 0x00 0x00

I've been told that the first few characters

0x53 0x69 0x75 0x64 0x69 0x5F 0x37 0x42

means

Siudi_7B

also

0x6D 0x00

means

109

so in my code I have this

message = "Siudi_7B 109 1 1"

which is equivalent to

0x53 0x69 0x75 0x64 0x69 0x5F 0x37 0x42 0x6D 0x00 0x04 0x00 0x01 0x00

Now the last few bytes I've not been given the meaning. And I'm supposed to figure it out. I've really tried my best but nothing yet.

So in short, I kindly need to know the string equivalent of

0x01 0x00

and

0x00 0x00 0x00 0x00

Upvotes: 2

Views: 11456

Answers (3)

olyboy16
olyboy16

Reputation: 66

Thanks guys, PM 2Ring's comment helped point me in the right direction.

So I figured the initail doc was wrong,

109 is not equivalent to 0x6D 0x00 109 is 0x31 0x30 0x39

So I'm just going to request more clarifications on the task. Thanks a lot everyone.

So in code I will have

message = b"\x31\x30\x39"

Upvotes: 0

KC.
KC.

Reputation: 3097

You should read module binascii or codecs if you want to know each characters hex.

import codecs,binascii
codes =[codecs.encode(i.encode(),"hex") for i in "Siudi_7B 109 1 1"]
print( codes )
bins  = [binascii.hexlify(i.encode()) for i in "Siudi_7B 109 1 1"]
print( bins )
for x in "Siudi_7B 109 1 1":
    print("{:5}".format(x),end="")
print()
print("0x"+" 0x".join([str(b.decode()) for b in  bins]) )

Upvotes: 0

blue note
blue note

Reputation: 29071

When you get the string binary from the socket, you binary.decode() to convert the input to a string. Similary, when you have a string to write to the socket, use string.encode() to convert it to binary.

Upvotes: 1

Related Questions