Pergunta

I'm Python newbie and would like to convert ASCII string into a series of 16-bit values that would put ascii codes of two consecutive characters into MSB and LSB byte of 16 bit value and repeat this for whole string...

I've searched for similar solution but couldn't find any. I'm pretty sure that this is pretty easy task for more experienced Python programmer...

Foi útil?

Solução

In simple Python:

s= 'Hello, World!'
codeList = list()
for c in s:
    codeList.append(ord(c))

print codeList

if len(codeList)%2 > 0:
    codeList.append(0)

finalList = list()
for d in range(0,len(codeList)-1, 2):
    finalList.append(codeList[d]*256+codeList[d+1])

print finalList

If you use list comprehensions:

s= 'Hello, World!'
codeList = [ord(c) for c in s]    
if len(codeList)%2 > 0:    codeList.append(0)
finalList = [codeList[d]*256+codeList[d+1] for d in range(0,len(codeList)-1,2)]

print codeList
print finalList

Outras dicas

I think the struct module can be helpful here:

>>> s = 'abcdefg'
>>> if len(s) % 2: s += '\x00'
... 
>>> map(hex, struct.unpack_from("H"*(len(s)//2), s))
['0x6261', '0x6463', '0x6665', '0x67']
>>> 

I am currently working on the same problem (while learning python) and this is what is working for me – I know it’s not perfect ;( - but still it works ;)

import re

#idea - char to 16
print(format(ord("Z"), "x"))
#idea - 16 to char
print(chr(int("5a", 16)))

string = "some string! Rand0m 0ne!"
hex_string = ''
for c in string:
    hex_string = hex_string + format(ord(c), "x")

del string

print(hex_string)

string_div = re.findall('..', hex_string)
print(re.findall('..', hex_string))

string2 = ''
for c in range(0, (len(hex_string)//2)):
    string2 = string2 + chr(int(string_div[c], 16))

del hex_string
del string_div

print(string2)

This definitely worked when I tested it, and isn't too complicated:

string = "Hello, world!"
L = []
for i in string:
    L.append(i) # Makes L the list of characters in the string
for i in range(len(L)):
    L[i] = ord(L[i]) # Converts the characters to their ascii values
output = []
for i in range(len(L)-1):
    if i % 2 == 0:
        output.append((L[i] * 256) + L[i+1]) # Combines pairs as required

with "output" as the list containing the result.

By the way, you can simply use

ord(character)

to get character's ascii value.

I hope this helps you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top