签名右移:哪个编译器使用逻辑移位 [英] Signed right shift: which compiler use logical shift

查看:104
本文介绍了签名右移:哪个编译器使用逻辑移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Visual Studio,Ubuntu的GCC,英特尔编译器,MinGW测试了右移。所有符号位的移位。我猜Xcode的GCC也一样。

I tested right shift with Visual Studio, Ubuntu's GCC, Intel compiler, MinGW. All shift in the sign bit. I guess Xcode's GCC does the same.

我知道该行为是实现特定的,但它看起来像所有主要的台式机/服务器编译器实现算术移位。是否有任何广泛使用的编译器不在符号位移位?

I know that the behavior is implementation specific, but it looks like that all major desktop/server compilers implement arithmetic shift. Are there any widely used compiler that doesn't shift in the sign bit?

谢谢。

推荐答案

C运行在许多不同的架构上。我的意思是很多不同的架构。你可以得到在嵌入式DSP和Cray超级计算机上运行的C代码。

C runs on a lot of different architectures. I mean a lot of different architectures. You can get C code running on an embedded DSP and on a Cray supercomputer.

大多数C标准的实现定义部分,只有打破晦涩的架构。例如,有DSP和Cray超级计算机,其中 CHAR_BIT 是一个巨大的像32或64.所以如果你尝试你的代码在x86上,也许如果你慷ous一个PowerPC,ARM或SPARC,你不可能遇到任何奇怪的情况。没关系。大多数代码这些天总是运行在一个面向字节的架构与二进制补码整数和算术移位。我毫不怀疑,在可预见的未来任何新的CPU架构将是一样的。

Most of the "implementation-defined" parts of the C standard that people take for granted really only do break on obscure architectures. For example, there are DSPs and Cray supercomputers where CHAR_BIT is something huge like 32 or 64. So if you try out your code on an x86, and maybe if you're generous a PowerPC, ARM, or SPARC, you're not likely to run into any of the really weird cases. And that's okay. Most code these days will always run on a byte-oriented architecture with twos-complement integers and arithmetic shifts. I have no doubt that any new CPU architectures in the foreseeable future will be the same.

但是让我们来看看整数的两个最常见的表示形式:二进制补码和二进制补码:

But let's look at the two most common representations for integers: twos-complement and ones complement:

switch ((-1) >> 1) {
case 0:
case -0:
    puts("Hello, one's complement world!");
    // Possibly sign-magnitude.
    break;
case -1:
    puts("Hello, two's complement world!");
    break;
default:
    puts("Hello, computer without arithmetic shift");
    break;
}

不要出汗。只要坚持 / 当你想划分,和>> 当你需要移位。即使坏的编译器也善于优化这些操作。 (请记住 x / 2!= x>> 1 如果 x

Don't sweat it. Just stick to / when you want to divide, and >> when you need to shift. Even bad compilers are good at optimizing these operations. (And remember that x/2 != x>>1 if x is negative, unless you're on a one's complement machine, which is almost certainly not true.)

标准确保如果(int)x 不为负,则(int)x>> n ==(unsigned)x>> n ,因此没有足够的空间让编译器做完全意外的事情。

The standard does guarantee that if (int) x is not negative, then (int) x >> n == (unsigned) x >> n, so there is not a lot of room for a compiler to do something completely unexpected.

这篇关于签名右移:哪个编译器使用逻辑移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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