将int值转换为unicode [英] Convert an int value to unicode

查看:402
本文介绍了将int值转换为unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pyserial,需要发送一些小于255的值.如果我发送int本身,则将发送int的ascii值.所以现在我将int转换为unicode值,并通过串行端口发送它.

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 unicode value and sending it through the serial port.

unichr(numlessthan255);

However it throws this error:
'ascii' codec can't encode character u'\x9a' in position 24: ordinal not in range(128)

将int转换为unicode的最佳方法是什么?

Whats the best way to convert an int to unicode?

推荐答案

只要使用chr(somenumber)即可获取int的1个字节的值,只要它小于256即可.然后pySerial将其发送正常.

Just use chr(somenumber) to get a 1 byte value of an int as long as it is less than 256. pySerial will then send it fine.

如果您正在考虑通过pySerial发送消息,那么查看标准库中的struct模块是一个[em>非常的好主意,它处理endian问题,打包问题以及几乎每一个问题的编码您可能需要的数据类型为1个字节或更多.

If you are looking at sending things over pySerial it is a very good idea to look at the struct module in the standard library it handles endian issues an packing issues as well as encoding for just about every data type that you are likely to need that is 1 byte or over.

这篇关于将int值转换为unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆