无需转换即可从有符号整数转换为无符号整数

标签 c

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 a signed int to an unsigned 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/

相关文章:

c - 为什么我的 C 代码出错

C中字符变量字符串的大小

c - 套接字编程 : Client printing garbage string

将 void 指针分配给非 void 指针的 C99 警告?

c - DCRaw 说我应该在 gcc 中使用 -O4 进行编译。 -O4存在吗?

将数字从 n 基数转换为整数

c - 如何使用 wc_EccPublicKeyDecode 在 Wolfssl 中导入 der 证书

c - 将 Dijkstra 算法修改为 A* 实现

c - 从用于写入的 FILE 副本中将数据读入数组

c++ - C/C++ 中的字符串重整