int isNegative(int x) {
return ((unsigned) x)>> 31;
}
我正在编写一个采用 32 位的函数,如果 x<0 则返回 1,否则返回 0。如何在不强制转换的情况下将有符号整数转换为无符号整数。
最佳答案
OP 有不同的隐含问题
a function that takes 32 bits and returns 1 if x<0, and 0 otherwise.
int isNegative(int x) {
return x < 0;
}
// or maybe return bool/_Bool
bool isNegative(int x) {
return x < 0;
}
// or pedantically
int isNegative(int_least32_t x) {
return x < 0;
}
// or pedantically and nearly universally portable,
int isNegative(int32_t x) {
return x < 0;
}
converting from signed int to unsigned int without casting (and)
How do I convert asigned int
to anunsigned int
without casting.
简单赋值
int i;
unsigned u = i;
尝试使用 >>>
将这两种风险实现定义的行为结合起来,应该避免,除非给出令人信服的理由。
EXAMPLE An example of implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right. C11§3.4.2 2
关于无需转换即可从有符号整数转换为无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39562259/