Chinaunix首页 | 论坛 | 博客
  • 博客访问: 387511
  • 博文数量: 81
  • 博客积分: 45
  • 博客等级: 民兵
  • 技术积分: 608
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-22 11:46
个人简介

一个愤青

文章分类

全部博文(81)

文章存档

2015年(40)

2014年(29)

2013年(11)

2012年(1)

我的朋友

分类: C/C++

2014-03-18 22:57:20

在C中,十六进制打印char型数据经常用到

常见的做法是

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int main(int argc, char **argv)
  3. {
  4.     char c = 0x12;

  5.     printf("%02x\n", c);
  6.     
  7.     return 0;
  8. }

上面的代码看似正确,但是只是在当c小于0x80的时候是正确的,
因为%x格式化的类型是int或unsigned int, 所以c会被提升为int,
当c大于等于0x80时会被当作负数处理,为保留符号位,因此提升时
c会变为0xffffff80, 显然不正确

正确的打印方法如下:

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int main(int argc, char **argv)
  3. {
  4.     char c = 0x80;

  5.     printf("%02x\n", (unsigned char)c);
  6.     
  7.     return 0;
  8. }

或者

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int main(int argc, char **argv)
  3. {
  4.     char c = 0x80;

  5.     printf("%02hhx\n", c);
  6.     
  7.     return 0;
  8. }

亦或者

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int main(int argc, char **argv)
  3. {
  4.     char c = 0x80;

  5.     printf("%02x\n", c & 0xff);
  6.     
  7.     return 0;
  8. }


阅读(12186) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

zsszss00002015-03-18 15:12:04

学习了