ascii string到16位值的序列

时间:2014-04-16 09:22:03

标签: python string 16-bit

我是Python的新手,并希望将ASCII字符串转换为一系列16位值,这些值将两个连续字符的ascii代码放入16位值的MSB和LSB字节中,并对整个字符串重复此操作。 ..

我已经搜索过类似的解决方案,但无法找到。我非常确定这对于经验丰富的Python程序员来说非常简单......

4 个答案:

答案 0 :(得分:0)

我认为struct module可以在这里提供帮助:

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

答案 1 :(得分:0)

我目前正在研究同样的问题(在学习python时)这对我有用 - 我知道它并不完美;( - 但仍然有效;)

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)

答案 2 :(得分:0)

当我测试它时,这绝对有效,并且不太复杂:

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

"输出"作为包含结果的列表。

顺便说一下,你可以简单地使用

ord(character)

获得角色的ascii值。

我希望这会对你有所帮助。

答案 3 :(得分:0)

在简单的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

如果您使用列表推导:

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