BUG: 传输的uicode码转汉字显示部分错误

1.BUG描述

pc下发文本信息,采用unicode编码形式,下位机单元接收后,需要将其解码成utf-8的编码形式显示出来,但是发现文本首部和尾部出现乱码。

2.BUG原因

原因很简单,解码的时候尾部和首部没有对齐。记录这个BUG主要是记录下汉字的编码方法。

3.修复方法

解码时对齐即可。

4.unicode编码

统一码(Unicode),它也叫万国码、单一码。Unicode的最大好处。就是将世界上所有的文字用2个字节统一进行编码。

5.UTF-8

英文是UCS Transfer Format。UTF-8就是专门对Unicode这套理论标准的一种具体实现。UTF-8、UTF-16 和 UTF-32本质上只是出于空间和时间的权衡。
UTF-8最大的一个特征就是变长存储的编码方式。它可以使用1 ~ 4个字节去存储不同的字符,根据不同的字符选择最合适的字节长度去进行存储。相对来说最节省空间。

6.代码实现

点击查看代码
//unsigned int codepoint :这里必须是32位,因为utf-8最长占用4个字节
int unicode_to_utf8 (unsigned int codepoint, char *str)
{
 char out[4];
 if (codepoint < 0x80)
 {
   out[0] = (char)codepoint;
   strncpy (str, out, 1);
   return 1;
 }
 else if (codepoint < 0x800)
 {
   out[0] = 0xC0 | (codepoint >> 6);
   out[1] = 0x80 | (codepoint & 0x0000003F);
   strncpy (str, out, 2);
   return 2;
 }
 else if (codepoint < 0x10000)
 {
   out[0] = 0xE0 | (codepoint >> 12);
   out[1] = 0x80 | ((codepoint & 0x00000FFF) >> 6);
   out[2] = 0x80 | (codepoint & 0x0000003F);
   strncpy (str, out, 3);
   return 3;
 }
 else
 {
   out[0] = 0xF0 | (codepoint >> 18);
   out[1] = 0x80 | ((codepoint & 0x0003FFFF) >> 12);
   out[2] = 0x80 | ((codepoint & 0x00000FFF) >> 6);
   out[3] = 0x80 | (codepoint & 0x0000003F);
   strncpy (str, out, 4);
   return 4;
 }
 return 0; 
}

/*
*将pc下发的"你好",转换为utf-8码显示
*/
uint8_t *p_content = p_data+2;
uint8_t utf8_offset;
char str_src[300] = {0};
char *ptr_str = str_src;
unsigned int codepoint;
for(uint8_t i=0; i< ((*data_len )-2) / 2; i++)    //  "/2": because ever unicode use 2 byte;
{
  	codepoint = *p_content ++;
  	codepoint = codepoint << 8;
  	codepoint |= *p_content ++;
  	utf8_offset =  unicode_to_utf8(codepoint, ptr_str);
  	ptr_str = ptr_str+utf8_offset;
}
*(++ptr_str) = '\0';
dbg_printf ("font_color = %d, bg_color = %d, str:%s\n",font_color,bg_color, str_src);

可以看到你好的unicode码和utf-8码

posted @   Charles_hui  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示