UTF8转整数问题

DAVID9785 2016-09-12 02:51:31
"A"这个字,在UTF8为一字节编码
16进位表示法为:41
10进位表示法为:65

"您"这个字,在UTF8为三字节编码
16进位表示法为:E6 82 A8
10进位表示法为:230 130 168


UTF8.txt内容为:您 \n A
我现在想将UTF8.txt内容转化成10进位表示法





#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
int x;int y;
char txt[80]="";

ifstream ifile("C:\\Users\\Gon\\Desktop\\UTF8.txt",ios::binary);
if(ifile.is_open())
{
while(!ifile.eof())
{
ifile >> txt;
cout << txt<< endl;

x=char (txt[0]);
switch(x)
{ case 0-127:
cout <<"1st byte~ " <<x << endl;
break;
case 240-247:
cout <<"1st byte~ " <<x << endl;
y=char (txt[1]);
cout <<"2nd byte~ " <<y << endl;
y=char (txt[2]);
cout <<"3rd byte~ " <<y << endl;
break;
default:
cout <<"1st byte~ " <<x << endl;
y=char (txt[1]);
cout <<"2nd byte~ " <<y << endl;
y=char (txt[2]);
cout << "3rd byte~ " <<y << endl;
y=char (txt[3]);
cout << "4th byte~ " <<y << endl;
y=char (txt[4]);
cout << "5th byte~ " <<y << endl;
y=char (txt[5]);
cout << "6th byte~ " <<y << endl;
}

}
}
else
cout << "fail to open file" << endl;
ifile.close(); // close file
system("pause");
return 0;
}






我想要得到的结果是:

1st byte~ 230
2nd byte~ 130
3rd byte~ 168
A
1st byte~ 65


可是实际跑出来的结果是:

1st byte~ -26
2nd byte~ -126
3rd byte~ -88
4th byte~ 0
5th byte~ 0
6th byte~ 0
A
1st byte~ 65
2nd byte~ 0
3rd byte~ -88
4th byte~ 0
5th byte~ 0
6th byte~ 0



几个问题点:
1. A的1st byte是65 应该代入case 0-127 可是实际上却代入default case 请问为何?
2. "A"跑出来是单字节 数值65没错 "您"跑出来是三个字节 数值完全不对而且还是负数 请问该如何修改?


感谢您的细心阅帖,谢谢!!
...全文
425 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ForestDB 2016-09-13
  • 打赏
  • 举报
回复
case 0-127: case -127: if (x >=0 && x <= 127) {
red-fly 2016-09-12
  • 打赏
  • 举报
回复
utf8.txt的内容是什么编码?如果不是utf8编码的话,读出来之后要先转换才行
小灸舞 2016-09-12
  • 打赏
  • 举报
回复
case 0-127达不到你想要的结果
改成if(x >= 0 && x <= 127)
  • 打赏
  • 举报
回复
引用 3 楼 q3733353520 的回复:
304 372
  • 打赏
  • 举报
回复
赵4老师 2016-09-12
  • 打赏
  • 举报
回复
case 0-127: 等价于 case -127:
paschen 2016-09-12
  • 打赏
  • 举报
回复
case 0-127: 不是表示 0到127,而是表示0-127=-127,即为-127的情况,其余同理

如果要限制某个范围,用if来判断比较好

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧