C十六进制常量类型 [英] C hex constant type

查看:245
本文介绍了C十六进制常量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的c代码:

  #include< stdio.h> 

int main(){
printf(%d \ n,-1>> 8);
返回0;
}

我使用-m32在x86_64上使用gcc 4.6.3编译此代码旗。我得到-1打印出来,如我所料,这种转变发生算术使用2的补码表示,导致-1。



现在如果我改写

  printf(%d \ n,0xFFFFFFFF>> 8); 

我得到了16777215.我希望这个常量被解释为int(signed),然后转换为算术,这将导致-1再次。我浏览了最新的C标准,似乎无法理解为什么会出现这种情况。任何想法?根据C99标准(6.4.4.1),十六进制常量将是此列表中的第一个类型,可以代表他们:

  int 
unsigned int
long int
unsigned long int
long long int
unsigned long long int

十六进制文字 0xFFFFFFFF 不符合 int (它可以将值 -0x80000000 0x7FFFFFFF ),但符合 unsigned int ,因此它的类型将是无符号的。将无符号值 0xFFFFFFFF 右移8将给出 16777215


I wrote the following c code:

#include <stdio.h>

int main () {
  printf("%d\n", -1 >> 8);
  return 0;
}

I compile this code with gcc 4.6.3 on my x86_64 using the -m32 flag. I get -1 printed out as I would expect, the shift occurs arithmetically using two's complement representation resulting in -1.

Now if I instead write

printf("%d\n", 0xFFFFFFFF >> 8);

I get 16777215. I would have expected this constant to be interpreted as an int (signed) and then the shift to be arithmetic which would result in -1 again. I've looked through the latest C standard and I can't seem to understand why this is the case. Any ideas?

解决方案

According to the C99 standard (6.4.4.1), hexadecimal constants will be the first type on this list that can represent them:

int
unsigned int
long int
unsigned long int
long long int
unsigned long long int

The hex literal 0xFFFFFFFF does not fit in an int (which can hold the values -0x80000000 to 0x7FFFFFFF), but does fit in unsigned int, and therefore its type will be unsigned. Right-shifting the unsigned value 0xFFFFFFFF by 8 gives 16777215.

这篇关于C十六进制常量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆