首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于sprintf解决思路

2012-10-05 
关于sprintf在百度百科里有这样一段:比如,假如我们想打印短整数(short)-1 的内存16 进制表示形式,在Win32

关于sprintf
在百度百科里有这样一段:
比如,假如我们想打印短整数(short)-1 的内存16 进制表示形式,在Win32 平台上,一个short 型占2 个字节,所以我们自然希望用4 个16 进制数字来打印它:
  short si = -1;
  sprintf(s, "%04X", si);
  产生“FFFFFFFF”,怎么回事?因为spritnf 是个变参函数,除了前面两个参数之外,后面的参数都不是类型安全的,函数更没有办法仅仅通过一个“%X”就能得知当初函数调用前参数压栈时被压进来的到底是个4 字节的整数还是个2 字节的短整数,所以采取了统一4 字节的处理方式,导致参数压栈时做了符号扩展,扩展成了32 位的整数-1,打印时4 个位置不够了,就把32 位整数-1 的8 位16 进制都打印出来了。
  如果你想看si 的本来面目,那么就应该让编译器做0 扩展而不是符号扩展(扩展时二进制左边补0 而不是补符号位):
  sprintf(s, "%04X", (unsigned short)si);
  就可以了。或者:
  unsigned short si = -1;
  sprintf(s, "%04X", si);
我有一个问题不太明白,之前说在short si = -1;sprintf(s, "%04X", si);中函数不知si是几个字节,所以输出错误。按理说,sprintf(s, "%04X", (short)si)就可以了,为什么还要加上unsigned呢?

[解决办法]
The short keyword can be preceded by either the keyword signed or the keyword unsigned. The int keyword is optional and can be omitted. To the MIDL compiler, a short integer is signed by default and is synonymous with signed short int.

[解决办法]
The short keyword can be preceded by either the keyword signed or the keyword unsigned. The int keyword is optional and can be omitted. To the MIDL compiler, a short integer is signed by default and is synonymous with signed short int.

[解决办法]

C/C++ code
产生“FFFFFFFF”,怎么回事?//因为你的机器是32位,而且你是用十六进制表示的,所以为8个F为什么还要加上unsigned呢?//因为你不知道它的范围,只知道是int类型,加上unsigned是为了增加它的存储范围。
[解决办法]
加上unsigned的意义在于用0去扩展符号位:
short类型的-1为0xffff,
1、当不用unsigned的时候,会用符号位1去扩展为int类型,所以值为0xffffffff;
2、当用unsigned的时候,会用0去扩展为int类型,所以值为0x0000ffff。

热点排行