漢字和unicode碼的轉換
暑假放假沒回家,留在學校做一個簡訊傳送的專案,漢字和unicode 碼的轉換把我弄的夠嗆的,剛開始用C語言來做,總是出現亂碼,卡了很久很久了,後來無意間在網上看見,說可以用qt實現,。。哈哈,剛好又在網上找到了一段程式碼,終於解決了。。。來來分享分享:
#ifndef WIDGET_H2 #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%
~