[英]ascii string to sequence of 16-bit values
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... 我是Python新手,想将ASCII字符串转换为一系列16位值,该值会将两个连续字符的ascii代码放入16位值的MSB和LSB字节,然后对整个字符串重复此操作...
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...
我敢肯定,对于经验丰富的Python程序员来说,这是一件容易的事...
I think the struct module can be helpful here: 我认为struct模块在这里可能会有所帮助:
>>> 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 ;) 我目前正在研究同一个问题(在学习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)
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. 获得角色的ascii值。
I hope this helps you. 我希望这可以帮助你。
In simple Python: 在简单的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.