汉字和unicode码的转换

来源:互联网 发布:null在c语言的作用 编辑:程序博客网 时间:2024/04/29 10:37

 暑假放假没回家,留在学校做一个短信发送的项目,汉字和unicode 码的转换把我弄的够呛的,刚开始用C语言来做,总是出现乱码,卡了很久很久了,后来无意间在网上看见,说可以用qt实现,。。哈哈,刚好又在网上找到了一段代码,终于解决了。。。来来分享分享:


 #ifndef WIDGET_H
  2 #define WIDGET_H
  3 #include<QWidget>
  4 class Widget:public QWidget
  5 {
  6         Q_OBJECT
  7
  8         public:
  9         Widget(QWidget *parent=0);
 10         QString  stringToUnicode(QString str);
 11         QString  unicodeToString(QString str);
 12
 13
 14 };
 15
 16
 17 #endif


 #include<QtGui/QApplication>
  2 #include<QString>
  3 #include <QObject>
  4 #include<QDebug>
  5 #include<QTextCodec>
  6 #include"main.h"
  7
  8
  9 Widget::Widget(QWidget *parent):QWidget(parent)
 10 {
 11 }
 12
 13 QString Widget::stringToUnicode(QString str)
 14 {
 15
 16
 17         // 这里传来的字符串一定要加tr,main函数里可以加 QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
 18
 19         //  例如:str=tr("你好");
 20
 21         const QChar *q;
 22
 23         QChar qtmp;
 24
 25         QString str0, strout;
 26
 27         int num;
 28
 29         q=str.unicode();
 30
 31         int len=str.count();
 32
 33         for(int i=0;i<len;i++)
 34
 35         {   qtmp =(QChar)*q++;
 36
 37                 num= qtmp.unicode();
 38
 39                 if(num<255)
 40
 41                         strout+="00"; //英文或数字前加"00"
42
 43
 44
 45                 str0=str0.setNum(num,16);//变成十六进制数
 46
 47
 48
 49                 strout+=str0;
 50
 51         }
 52
 53
 54
 55
 56
 57         return strout;
 58
 59
 60
 61 }
 62
 63 QString Widget::unicodeToString(QString str)
 64
 65 {
 66
 67         //例如 str="4F60597D";
 68
 69         int temp[400];
 70
 71         QChar qchar[100];
 72
 73         QString strOut;
 74
 75         bool ok;
 76
 77         int count=str.count();
 78
 79         int len=count/4;
 80
 81         for(int i=0;i<count;i+=4)
 82


 83         {
 84
 85                 temp[i]=str.mid(i,4).toInt(&ok,16);//每四位转化为16进制整型
 86
 87                 qchar[i/4]=temp[i];
 88
 89                 QString str0(qchar, len);
 90
 91                 strOut=str0;
 92
 93         }
 94
 95         return strOut;
 96
 97 }
 98
 99 int main(int argc,char *argv[])
100 {
101
102         QApplication app(argc,argv);
103
104         Widget *wid=new Widget;
105
106         QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
107         QString str_c=QObject::tr("工作愉快!");
108
109         //QString str="5DE54F5C61095FEBFF01";//工作愉快的unicode 码
110          QString str= "5de54f5c61095feb00200021";//也是工作愉快的unicode码
111
112         QString str1=wid->unicodeToString( str);
113         QString str2=wid->stringToUnicode(str_c);
114
115         qDebug()<<str1;
116         qDebug()<<str2;
117
118         return app.exec();
119
120
121 }

终于可以回家好好过暑假,然后迎接我的大3了!!!                                                                                                                                     79,1-8        50%


~           




原创粉丝点击