C++位移运算符左移怎么计算出int(有符号)所能表示的最大值?
巴扎黑
巴扎黑 2017-04-17 14:27:46
0
6
604

我尝试使用了1<<31,结果得到的值是int的最小值。。。
这是为什么?

巴扎黑
巴扎黑

reply all(6)
刘奇

Because the default 1 here is int 类型。而你的编译环境下,int` is 32-bit.
Then the binary representation of this 1 is

0000 0000 0000 0000 0000    0000 0000 0000 0001

After shifting left by 32 bits

1000 0000 0000 0000 0000    0000 0000 0000 0000

Because it is of int type, it is signed. So the first bit is the sign bit, which is a negative number. Why is it the minimum value of int? Because it is expressed using complement code.

If you need to move out of the maximum value, use the following method

((unsigned int)-1) >> 1

Because the binary representation of -1 is 0xffffffff. If you convert it to an unsigned type and then shift it, there will be no impact of the sign bit.

刘奇

The maximum int is 2 to the 31st power - 1, 1<<31 is out of range, and will be calculated backwards from the smallest negative number

洪涛

For a 32-bit int, shifting 31 bits left will reach the highest bit
For a signed number, the highest bit is the sign bit, 0 is positive and 1 is negative, so it becomes the minimum value. The specific reason can be Take a look at how int is stored

阿神

(1 << 31) - 1 : The maximum value of signed int
(1 << 31) + 1 : The minimum value of signed int

((unsigned int)1<<32)-1: The maximum value of unsigned int
0: The minimum value of unsigned int

阿神

I tested it:

#include <stdio.h>

#define STR(x) #x
#define PRINT(x) printf("hex: 0x%08x, dec: %12d, str: \"%s\"\n", x, x, #x )

int main(){
    puts( "全 0 & 全 1" );
    PRINT( 0 );
    PRINT( -1 );

    puts( "\n全 1 的左右 shift" );
    PRINT( -1>>1 );
    PRINT( -1<<1 );

    puts( "\n减法优先级更高" );
    PRINT( 1<<31-1 );
    PRINT( 1<<30 );

    puts( "\n怎么得到 int 的最大正数" );
    PRINT( 0x7FFFFFFF );
    PRINT( 1<<31 );
    PRINT( ((unsigned)1<<31)-1 );
    PRINT( (int)(((unsigned)1<<31)-1) );
    PRINT( ((unsigned int)-1)>>1 );
    PRINT( -1>>1 );

    return0;
}

Compile: gcc test.c -o test,

Run: ./test

Result:

全 0 & 全 1
hex: 0x00000000, dec:            0, str: "0"
hex: 0xffffffff, dec:           -1, str: "-1"

全 1 的左右 shift
hex: 0xffffffff, dec:           -1, str: "-1>>1"
hex: 0xfffffffe, dec:           -2, str: "-1<<1"

减法优先级更高
hex: 0x40000000, dec:   1073741824, str: "1<<31-1"
hex: 0x40000000, dec:   1073741824, str: "1<<30"

怎么得到 int 的最大正数
hex: 0x7fffffff, dec:   2147483647, str: "0x7FFFFFFF"
hex: 0x80000000, dec:  -2147483648, str: "1<<31"
hex: 0x7fffffff, dec:   2147483647, str: "((unsigned)1<<31)-1"
hex: 0x7fffffff, dec:   2147483647, str: "(int)(((unsigned)1<<31)-1)"
hex: 0x7fffffff, dec:   2147483647, str: "((unsigned int)-1)>>1"
hex: 0xffffffff, dec:           -1, str: "-1>>1"
Ty80

Brother, remove the sign bit and shift it by 30 bits

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!