c - C中位移位和算术的位宽

标签 c math bit-manipulation

我正在开发一个混合 64 位(用于某些计算)和 32 位(用于节省空间存储)无符号整数的程序,因此在算术过程中将它们分类以避免溢出非常重要

这是一个示例问题

我想将 1 向左移动一个 unsigned long n,但我希望结果是一个 unsigned long long。这将用于 if 语句中的比较操作,因此没有进行赋值。我会给你一些代码。

void example(unsigned long shift, unsigned long long compare)
{
    if((1<<shift)>compare)
    {
        do_stuff;
    }
}

我怀疑这不会做我想做的事,那么下面会做我想做的事吗?

void example(unsigned long shift, unsigned long long compare)
{
    if(((unsigned long long)1<<shift)>compare)
    {
        do_stuff;
    }
}

如何对这些东西的位宽进行微观管理?哪个操作数决定执行操作的位宽,还是两者中较大的一个?

此外,如果可能的话,我还想了解一下它如何适用于其他操作,例如 + */% 等。

也许对具有此信息的资源的引用会很好,我似乎无法在任何地方找到此信息的明确说明。或者规则很简单,只需发布​​即可。我不确定。

最佳答案

Which operand determines the bit width that the operation is performed with, or is it the larger of the two?

对于位移位,左操作数(要移位的操作数)决定执行操作的类型。如果整数提升将其转换为 intunsigned int,则以该类型执行操作,否则以左操作数的类型执行操作。

为了进行比较,移位的结果可能会被转换为另一个操作数的类型。在您的示例代码中,整数常量 1 的类型为 int,因此转换将以 int 类型执行,转换的结果到 unsigned long long 进行比较。转换有效,因为结果的类型不会因整数提升而改变,就像使用带后缀的文字 1ull 一样。

对于其他列出的操作,算术运算(至于比较),执行操作的类型由两个操作数确定,如下所示:

Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:

  • If both operands have the same type, then no further conversion is needed.
  • Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
  • Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
  • Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
  • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

关于c - C中位移位和算术的位宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12666330/

相关文章:

c - 为什么我无法打开文件?

python - 如何在 PYTHON 中创建 bool 指标矩阵

algorithm - 计算给定侧的法线

java - 将 Char 更改为具有相同位结构的 Short。 (2的补码问题)

c - 用C广播UDP

作为整数的变量的命令行参数

Java:从输入字符串数组生成 nCr 数组并返回它

c++ - 如何用位运算代替取模和除法运算?

php - PHP 7 和 1 中的工作原理

c - 如何通过套接字发送 XDR 结构内的数组