【问题标题】:ascii string to sequence of 16-bit valuesascii 字符串到 16 位值序列
【发布时间】:2014-05-31 01:41:50
【问题描述】:

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

我已经搜索过类似的解决方案,但找不到任何解决方案。我很确定这对于更有经验的 Python 程序员来说是一件很容易的事......

【问题讨论】:

  • 向我们展示 1) 输入,2) 所需输出,3) 您的代码,4) 实际输出。
  • - Python 2 还是 3? - 16 位作为字节字符串?
  • 字符串中的字符列表:['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'] ascii 代码序列:[72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 0]期望的结果(将 ascii 码对打包成 16 位值) [a, b, c] 其中 a=72*256+101, b=108*256+111 ...

标签: python string 16-bit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为struct module 在这里会有所帮助:

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

    【讨论】:

      【解决方案3】:

      我目前正在解决同样的问题(在学习 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)
      

      【讨论】:

        【解决方案4】:

        这在我测试时确实有效,并且不是太复杂:

        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值。

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-08
          • 1970-01-01
          • 1970-01-01
          • 2020-12-06
          • 1970-01-01
          • 2021-12-22
          • 2011-09-15
          • 2012-08-02
          相关资源
          最近更新 更多