中文的编码显示常常是一个让人头痛的问题,网络传输的时候中文也会变成二进制的流,接收方显示就成了一个大问题。

今天使用python的struct模块来对数据封包解包,同样有这个问题。解决方法是:一般会把python代码文件声明为utf-8编码,这样可以直接在里面写中文。正常封包,接收的数据使用utf-8解包,要打印出中文字符,可以使用unicode操作。举例如下

1 # -*- coding: utf-8 -*-
2 import struct
3 s = '哈哈'
4 print s, len(s)
5 sp = struct.pack('=6s', s)
6 print sp
7 dp = struct.unpack('=6s', sp)
8 print dp, dp[0], type(dp[0]), len(dp[0]), str(dp[0]), len(str(dp[0]))
9 print unicode(dp[0], 'utf-8')

相应的输出如下

struct发送与显示中文

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
  • 2021-06-26
  • 2021-11-28
猜你喜欢
  • 2021-08-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-01-05
相关资源
相似解决方案