如何在 C/C++ 中执行无符号右移(Java 中的>>>)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2429479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:06:38  来源:igfitidea点击:

How do I perform an unsigned right shift (>>> in Java) in C/C++?

javacbit-manipulation

提问by changed

How do I perform an unsigned right shift (>>> in Java) in C/C++?

如何在 C/C++ 中执行无符号右移(Java 中的>>>)?

采纳答案by John Knoeller

>>>is unsigned right shift, so I would think that in C this would be the same as

>>>是无符号右移,所以我认为在 C 中这将与

unsigned int foo;
unsigned int bar = foo >> whatever;

回答by Stephen Canon

In C, to get an unsigned shift, you just do a shift on an unsigned type.

在 C 中,要获得无符号移位,您只需对无符号类型进行移位。

unsigned int result = (unsigned int)valueToBeShifted >> shiftAmount;

Note that there is no guarantee that >>on a signed type gives you a signed shift in C -- this is implementation defined behavior. Most common implementations produce a signed shift if the type is signed, however.

请注意,不能保证>>有符号类型会在 C 中为您提供有符号转换——这是实现定义的行为。但是,如果类型是有符号的,则最常见的实现会产生有符号移位。