刚写个字符转换的函数

/*! \brief 将一个字符从一种编码转换到另外一种编码
*
* \param \li \c val 要转换的字符。例如36229
* \param \li \c encTo 转换为什么编码格式,例如"GB2312"
* \param \li \c encFrom val的编码格式。例如"UTF-16"
* \return 转换的结果,例如"超"
*
*/
std::string convChar(uint32_t val,const char* encTo,const char* encFrom){
    iconv_t pt=iconv_open(encTo,encFrom);
    if(pt== (iconv_t)-1){
        std::cout<<"iconv_open 失败"<<std::endl;
    }
    iconv(pt,NULL,NULL,NULL,NULL);
    uint8_t x[8];
    uint8_t* p=x;
    *(reinterpret_cast<uint16_t*>(p))=0xfeff;
    p+=2;
    *(reinterpret_cast<uint32_t*>(p))=val;
    p+=4;
    *(reinterpret_cast<uint16_t*>(p))=0;
    const char * str=(const char*)x;
    char* out=new char[100];
    size_t b=100;
    const char** in=&str;
    size_t lenin=sizeof(x);
    char* buf=out;
    int ret=iconv(pt,in,&lenin,&out,&b);
    if(ret){
        std::cout<<"转换失败\n";
        switch(errno){
        case E2BIG:
            THROW("There is not sufficient room at *outbuf.\n");
            break;
        case EILSEQ:
            THROW(" An invalid multibyte sequence has "
            "been encountered in the input.\n");
            break;
        case EINVAL:
            THROW(" An incomplete multibyte sequence has been encountered
            in the input.\n");
            break;
        default:
            THROW("未知的errno\n");
        }
    }
    iconv_close(pt);
    return buf;
}

e.g.

#include "decode.h"
#include <iostream>
#include "exceptions.h"

int main(int argc,char* argv[]){
    try{
        int val=36229;
        std::string s=convChar(val,"GB2312","UTF-16");
        std::cout<<s<<std::endl;
    }
    catch( except& ex){
        std::cout<<ex<<std::endl;
    }
    catch(std::exception& ex){
        std::cout<<ex.what()<<std::endl;
    }
    catch(...){
        std::cout<<"未知的异常"<<std::endl;
    }
    return 0;
}

此博客中的热门博文

少写代码,多读别人写的代码

在windows下使用llvm+clang

tensorflow distributed runtime初窥