cout输出字符的ASCII码值的问题

AFreshGirl 2011-04-26 09:05:48
char c = -1;

如果用语句:printf("%d",(unsigned char)c)将输出255

若用cout怎么实现输出255?
这样cout<<(unsigned int)c<<endl;不行啊
...全文
951 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
AFreshGirl 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 zhouzhangkui 的回复:]

这里同样的帖子?
C/C++ code

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <windows.h>// 注意添加 才能使用byte
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{……
[/Quote]
不好意思,刚在这里发了好久没人回复,然后我又到C++builder板块发了一次
fyw1990 2011-04-26
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <math.h>

void main()
{
char c=-1;
cout << ((unsigned int)c&0xff) << endl;
}


周药师 2011-04-26
  • 打赏
  • 举报
回复
这里同样的帖子?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <windows.h>// 注意添加 才能使用byte
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
char c = -1;
cout<<int(BYTE(c))<<endl; //255
getch();
return 0;
}

AFreshGirl 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 kid_coder 的回复:]

cout<<dec<<(unsign……
[/Quote]
我这样可以实现了

cout<<int(unsigned char (c))<<endl;

不知道怎么理解。。。
KID_coder 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 liqiac 的回复:]
引用 4 楼 heartwasnot 的回复:

-1的二进制表示是11111111然后。转换成无符号,也就是第一位不表示符号位了。。这个时候就成了255
而你转换成无符号整形,因为整形是四字节,而不是1字节。。。所以不是二进制11111111,也就不是255了

那怎么改?

C/C++ code

cout<<dec<<(unsigned char)c;


也不行啊
[/Quote]


#include <stdio.h>
#include <math.h>

void main()
{
char c=-1;
cout << ((unsigned int)c&0xff) << endl;
}

满足你~ 主要是和0xff做&操作~把前三个字节都设置成0~ 剩下一个字节1111 1111 输出255
AFreshGirl 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 heartwasnot 的回复:]

-1的二进制表示是11111111然后。转换成无符号,也就是第一位不表示符号位了。。这个时候就成了255
而你转换成无符号整形,因为整形是四字节,而不是1字节。。。所以不是二进制11111111,也就不是255了
[/Quote]
那怎么改?

cout<<dec<<(unsigned char)c;

也不行啊
HeartWasNot 2011-04-26
  • 打赏
  • 举报
回复
-1的二进制表示是11111111然后。转换成无符号,也就是第一位不表示符号位了。。这个时候就成了255
而你转换成无符号整形,因为整形是四字节,而不是1字节。。。所以不是二进制11111111,也就不是255了
AFreshGirl 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 kid_coder 的回复:]

255不是-1的ascii值
char c = -1;
则c的值为~
1111 1111
若为无符号数~ 则是255

-1若为int类型~则占4个字节
存储为
1111 1111 1111 1111
以unsigned int类型输出为4294967295
[/Quote]
我现在的意思就是怎么把这个1111 1111当成无符号十进制数输出来
未注销 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 kid_coder 的回复:]

255不是-1的ascii值
char c = -1;
则c的值为~
1111 1111
若为无符号数~ 则是255

-1若为int类型~则占4个字节
存储为
1111 1111 1111 1111
以unsigned int类型输出为4294967295
[/Quote] .
KID_coder 2011-04-26
  • 打赏
  • 举报
回复
255不是-1的ascii值
char c = -1;
则c的值为~
1111 1111
若为无符号数~ 则是255

-1若为int类型~则占4个字节
存储为
1111 1111 1111 1111
以unsigned int类型输出为4294967295



64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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