繁体   English   中英

类型转换:在C中将signed int转换为unsigned long

[英]Type conversion: signed int to unsigned long in C

我目前正在学习C编程语言(K&R)的第二章,并了解按位运算。

这是激发我好奇心的例子:

x = x & ~077

假设一个16位字长和32位长型 ,我认为会发生的是077首先会被转换为:

0000 0000 0011 1111 (16 bit signed int).

然后将其补充为:

1111 1111 1100 0000.

我的问题是,对于不同的x类型,接下来会发生什么? 如果x是一个有符号的int,则答案很简单。 但是,如果x是一个有符号的长整数,我假设〜077将变为:

1111 1111 1111 1111 1111 1111 1100 0000

以下2s补码以保留符号。 它是否正确?

同样,如果x是一个无符号的long,则〜077将变为:

0000 0000 0000 0000 1111 1111 1100 0000

或者,将〜077首先转换为签名长整型:

1111 1111 1111 1111 1111 1111 1100 0000

...之后将其转换为无符号长整数(位无变化)?

任何帮助都会帮助我弄清楚此操作是否总是将最后6位始终设置为零。

无论选择哪种数据类型, ~077都会将最右边的6位设置为0 ,将所有其他6位设置为1

假设有16位int和32位long ,则有4种情况:

情况1

unsigned int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
unsigned long y = ~x; // y = 0000 0000 0000 0000 1111 1111 1100 0000

情况二

unsigned int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
long y = ~x; // y = 0000 0000 0000 0000 1111 1111 1100 0000

情况3

int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
unsigned long y = ~x; // y = 1111 1111 1111 1111 1111 1111 1100 0000

案例4

int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
long y = ~x; // y = 1111 1111 1111 1111 1111 1111 1100 0000

在这里查看代码。 这意味着在对源进行signed时便完成了符号扩展。 当源为unsigned ,不扩展符号位,并且将左位设置为0

 x = x & ~077    //~077=11111111111111111111111111000000(not in every case)

~077 is a constant evaluated at the complie time so its value will be casted according to the value of x at the compile time因此AND操作将始终将x的最后6位转换为0,其余位将保持不变在AND运算之前。 喜欢

//let x=256472--> Binary--> 0000 0000 0000 0011 1110 1001 1101 1000
 x = x & ~077;
// now x = 0000 0000 0000 0011 1110 1001 1100 0000 Decimal--> 256448

因此,在编译期间,不管数据类型如何,最后6位都将变为0,其余位保持不变。 并以knr The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.写在The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time. 〜077是The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM