目标:接收网络传过来的字节序,转换字符串
全英文的情况下直接保存string即可,带中文的情况试了好久故做如下记录。
1. 首先确认gcc 应该是utf-8的格式来存储字符串的
通过cmake 加入-fexec-charset=xxx报错如下
add_compile_options(-fexec-charset=xxx)
/usr/lib/gcc/x86_64-linux-gnu/5/include-fixed
/usr/include/x86_64-linux-gnu
/usr/include
End of search list.
cc1plus: error: conversion from UTF-8 to GBKA not supported by iconv
2. 确认网络传输的字节格式
由于网络传来的数据是GB2312, 通过gdb变量内容显示
gdb) p m_dataBuffer
$1 = std::vector of length 65536, capacity 65536 = {206 '\316', 210 '\322',
“我” 的GB2312编码:CED2,正好和发送内容一致。所以首先想着改成GB2312来存字符串,这样就不用转换接收到的数据。
编译指定上面的属性为GB2312,但是偿试了几次,调试发现字符串并没有显示成中文,还是两个字节的CE D2。
3. 转换成UTF-8
最后还是把接收的字节,转换成utf-8存储在string。
调用m_iconv = iconv_open(toCharset, fromCharset);包含头文件#include <codecvt>。
然后调用转换接口,iconv(m_iconv, &input, static_cast<size_t*>(&inLen),
&output, static_cast<size_t*>(&outLen));
由于utf-8 可能是4个字节的,这个地方也把自己坑了,一直没转换成功....
output需要是input接收字节的2倍
std::unique_ptr<char*> dataBuffer = std::make_unique<char*>(new char[size * 2 + 1]);
这样再调API时就成功,显示中文了。