c - Left shifting operation on int -


on indiabix.com came across following question.as per experience level(beginner in c) output of above should 0 (10000000 << 1 00000000) came out 256,after going deeper found printing using %d supports 4 bytes output 256 instead of 0.

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

now consider following example

#include<stdio.h>  int main() {     unsigned int = 2147483648;(bit 31 = 1 , b0 b30 0)     printf("%d \n", i<<1);     return 0; } 

when left shift above 0 output, %d supports value of int output should 0 when changed %d %ld output still 0. %ld supports values upto long int output should not 0.why getting 0 output.

in first case, i promoted int, can store @ least 32767, shift calculated. result, result became 256.

in second case, if unsigned int 32-bit long, calculated in unsigned int , result wraps. result, result became 0.

you have cast larger type want.

#include<stdio.h> #include<inttypes.h>  int main() {     unsigned int = 2147483648;//(bit 31 = 1 , b0 b30 0)     printf("%"priu64" \n", (uint64_t)i<<1);     return 0; } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -