Convert string to ASCII value python

后端 未结 8 1717
深忆病人
深忆病人 2020-12-07 22:43

How would you convert a string to ASCII values?

For example, \"hi\" would return 104105.

I can individually do ord(\'h\') and ord(\'i\'), but it\'s going to

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 23:17

    your description is rather confusing; directly concatenating the decimal values doesn't seem useful in most contexts. the following code will cast each letter to an 8-bit character, and THEN concatenate. this is how standard ASCII encoding works

    def ASCII(s):
        x = 0
        for i in xrange(len(s)):
            x += ord(s[i])*2**(8 * (len(s) - i - 1))
        return x
    

提交回复
热议问题