C 中位移位行为的差异

问题描述 投票:0回答:1

我正在运行一个简单的程序来了解位移位在 C 中的操作方式。表达式 (temp << n) / 2^n is indeed equivalent to temp as I see. Reasoning this, it seems that the left shift operation effectively multiplies temp by 2^n, and then dividing by 2^n cancels out this multiplication, leaving the original value of temp. In this simple program, I get temp for n = 4 and 9 but not for n = 12. For n=12, I get 100679. Why is the behavior different for n=12? I see that we shouldnt be having any overflows for n=12 so I'm curious why this is happening.

这是代码片段:

#include <stdio.h>
#include <stdint.h>
#include "math.h"

int main() {
    uint32_t temp = 5343559;
    printf("%u\n", ((temp << 4)/(uint32_t)(pow(2, 4)) )); 
    printf("%u\n", ((temp << 9)/(uint32_t)(pow(2, 9)) )); 
    printf("%u\n", ((temp << 12)/(uint32_t)(pow(2, 12)) )); 

    return 0;
}

谢谢你。

c bit bit-shift
1个回答
0
投票

将您的数字 5343559 视为其二进制表示形式。它声明为无符号 32 位数字,因此它看起来像这样:

00000000010100011000100101000111

注意最高有效位距左侧仅 9 位。因此,您只能左移 9,直到开始出现进位问题。

温度<< 4:

00000101000110001001010001110000

温度<< 9:

10100011000100101000111000000000

温度<< 12

00011000100101000111000000000000
© www.soinside.com 2019 - 2024. All rights reserved.