Convert an int value to unicode

前端 未结 4 833
臣服心动
臣服心动 2020-12-30 23:18

I am using pyserial and need to send some values less than 255. If I send the int itself the the ascii value of the int gets sent. So now I am converting the int into a unic

4条回答
  •  难免孤独
    2020-12-30 23:47

    Use the chr() function instead; you are sending a value of less than 256 but more than 128, but are creating a Unicode character.

    The unicode character has to then be encoded first to get a byte character, and that encoding fails because you are using a value outside the ASCII range (0-127):

    >>> str(unichr(169))
    Traceback (most recent call last):
      File "", line 1, in 
    UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 0: ordinal not in range(128)
    

    This is normal Python 2 behaviour; when trying to convert a unicode string to a byte string, an implicit encoding has to take place and the default encoding is ASCII.

    If you were to use chr() instead, you create a byte string of one character and that implicit encoding does not have to take place:

    >>> str(chr(169))
    '\xa9'
    

    Another method you may want to look into is the struct module, especially if you need to send integer values greater than 255:

    >>> struct.pack('!H', 1000)
    '\x03\xe8'
    

    The above example packs an integer into a unsigned short in network byte order, for example.

提交回复
热议问题