简体   繁体   中英

how to convert string to byte[]

When I translate txt file to byte operation I encounter some problems.

  • Example little is the only words in `test.txt.
  • The result of encoded by ascii code is 6c6974746c65 .
  • I want to execute byte operation like data[0x2]|data[0x3]<<8 means 0x74 | (0x74)<<8 =0x7474 data[0x2]|data[0x3]<<8 means 0x74 | (0x74)<<8 =0x7474 .

     f = open('test.txt','rb') output = f.read() f.close() file_size = len(output) print output,type(output) output_ascii = output.encode("hex") print output_ascii , type(output_ascii) , len(output_ascii) print output_ascii[0],output_ascii[1]` 

Result

little ('type str')  
6c6974746c65 (type 'str') 12  
6 c

I would like to get output_ascii[0] = 0x6c , output_ascii[1] = 0x69 ...etc

How should I modify?

byte = ''
total_byte = []

with open('test.txt','rb') as f:
    output = f.read() 
    print output, type(output)
    for ele in output:
        byte = ele.encode("hex")
        total_byte.append(byte)
        print byte ,type(byte)

print total_byte[0], total_byte[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM