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

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

问题描述

我测试与Visual Studio,Ubuntu的GCC,英特尔编译,MinGW的右移。在符号位全部移位。我想X code'S 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同时运行了很多不同的架构。我的意思是不同的体系结构的一个的很多的。你可以得到C code对嵌入式DSP和一个Cray超级运行。

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。因此,如果你尝试一下你的code在x86上,也许你再大方的PowerPC,ARM,或SPARC,你可能不会遇到任何的非常奇怪的情况。这没关系。最code这几天会一直与二进制补码整数算术移位面向字节的架构上运行。我毫不怀疑,在可预见的将来任何新的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.

不过,让我们来看看最常见的两种重presentations整数:二进制补码和的补:

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 ==可(签名)x>> ñ,所以没有很大的空间供编译器做一些完全出乎意料的。

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天全站免登陆