selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Details about ord and chr. #5

Open selfboot opened 7 years ago

selfboot commented 7 years ago

In file common.py

def compat_ord(s):
    if type(s) == int:
        return s
    return _ord(s)

def compat_chr(d):
    if bytes == str:
        return _chr(d)
    return bytes([d])

_ord = ord
_chr = chr

ord and chr is used.

ord

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.

In python 2.* :

Understanding so, you can know the following code:

>>> print ord("中")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 3 found
>>> print ord(u"中")
20013
>>> len(u'中')
1
>>> len('中')
3

chr

Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range.

>>> chr(12)
'\x0c'
>>> chr(256)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)

Another similar function is unichr(i): return the Unicode string of one character whose Unicode code is the integer i.