nani92
nani92

Reputation: 67

How to concatenation hexadecimal numbers?

I need to extract data from a text file where it is written by this way:

ccddeeff8899aabb4455667700112233

So my first question is how to convert the plaintext in order to have this format:

DATA= '\xcc\xdd\xee\xff\x88\x99\xaa\xbb\x44\x55\x66\x77\x00\x11\x22\x33'

My goal after that is to concatenate the extracted data from file with the START_OF_DATA='\x24'.

My second question is how concatenate DATA+START_OF_DATA. In fact, at first when I test my work I just used just one plaintext, so I used this declaration:

clear_msg=(b'\x24\xcc\xdd\xee\xff\x88\x99\xaa\xbb\x44\x55\x66\x77\x00\x11\x22\x33')

I need in the end to have exactly this same format.

This is my script in python:

import string
import serial
import time
from array import array
import struct

with open('C:\\Users\\user\\Plaintext.txt') as f:
    lines = f.readlines()

SOF= '\x24'
ser = serial.Serial(port='COM4',\
                    baudrate=230400,\
                    parity=serial.PARITY_NONE,\
                    stopbits=serial.STOPBITS_ONE,\
                    bytesize=serial.EIGHTBITS,\
                    timeout=0)

for a in range (0,1):
   line_array=lines[a]
   plaintxt_16b=line_array[0:32]

#The result is ccddeeff8899aabb4455667700112233

#clear_msg= SOF+plaintxt_16b
# print(clear_msg)
# ser.write(clear_msg)
time.sleep(0.4)

#while True:
#  print(ser.read(70))
ser.close()                # close ports

This is my text file Plaintext.txt:

ccddeeff8899aabb4455667700112233

Upvotes: 0

Views: 1334

Answers (1)

Drathier
Drathier

Reputation: 14539

You can simply use binascii.unhexlify. Then you can simply concatenate strings until you have what you need.

from binascii import unhexlify
res = unhexlify("ccddeeff8899aabb4455667700112233")
print("\x24" + res)

Upvotes: 2

Related Questions