Left switch operation to int

At IndiaBix.com, I came across the following question. According to my experience level (new to C), the output above should be 0 (10000000 << 1 is 00000000), but it turned out to be 256, after I went deeper, I found that we print using % d , which supports 4 bytes, so the output is 256 instead of 0.

#include<stdio.h> 
    int main()
    {
        unsigned char i = 128;
        printf("%d \n", i << 1);
        return 0;
    }

Now consider the following example

#include<stdio.h>

int main()
{
    unsigned int i = 2147483648;(bit 31 = 1 and b0 to b30 are 0)
    printf("%d \n", i<<1);
    return 0;
}

When I left the shift above, I get 0 as output, As% d supports int, the output should be 0, but when I changed% d to% ld, the result is still 0. Since% ld supports values ​​longer than int output should be 0. Why am I getting 0 as output.

+4
source share
5

i int, 32767, . 256.

, unsigned int 32 , unsigned int, . 0.

, , .

#include<stdio.h>
#include<inttypes.h>

int main()
{
    unsigned int i = 2147483648;//(bit 31 = 1 and b0 to b30 are 0)
    printf("%"PRIu64" \n", (uint64_t)i<<1);
    return 0;
}
+2

%d %ld.

, , unsigned int 4 .

%ld unsigned int. undefined.

+2

, 2147483648 (80000000h) 32- int, int, printf , %d. %u.

, , 0x80000000 << 1 0, unsigned int - 32 .

printf %ld ! , , .

char print. , %d, , printf ( ) int. , int , , %d.

my_char << n <<, , int, .

, C . .

+1

C (6.5.7 )

3 . - ....

(6.3.1.1 , )

  1. ... int ( > , ), int; unsigned int. .58) .

, int unsigned char, int unsigned char.

,

i << 1

i int, (, int 32 )

0x00000080 << 1

0x00000100

256

printf("%d \n", i << 1);

.

unsigned int i = 2147483648;(bit 31 = 1 and b0 to b30 are 0)
printf("%d \n", i<<1);

i

0x80000000

, int.

, i, int.

0x00000000

0

printf("%d \n", i<<1);

it will correctly output this zero, because its representation is the same for whole objects without sign and sign.

Even if you write, for example,

printf( "%lld \n", ( long long int )( i<<1 ));

you get the same result because the type of expression i << 1is anywayunsigned int

However, if you write

printf( "%lld \n", ( long long int )i << 1 );

then the operand iwill be converted to type long long int, and you will get

0x0100000000
0
source

Changing% d to% id will not be effective Change the data type to unsigned so that it increases your integer limit

0
source

All Articles