c - The difference between ~(x-1) and ~x+1 when x=0x80000000 -


the language use c. type of x , n int.

i have 1 line code following

  printf("x=%x,n=%d,first=%x,second=%x\n",x,n,((~(x+0xffffffff))>>n),((~x+1)>>n)); 

it shows value of x,n , 2 methods of shifting n bits of complement number of x. when x=0x80000000,~(x+0xffffffff)=0x8000000,~x+1=0x80000000, yet when shift these 2 n bits, results different.

btw, if changed 0xffffffff ~1+1(that means ~(x+(~1+1)), result same ~x+1

i wonder why happened. thanks.

the deleted answer pavan manjunath had correct answer 1 case, assuming int usual 32-bit type. integer constant

0xffffffff 

has value 2^32 - 1 , isn't representable int, representable unsigned int. type unsigned int (6.4.4.1). hence x converted unsigned int addition, and

((~(x+0xffffffff))>>n) 

evaluates as

((~(0x80000000u + 0xffffffffu)) >> n) ((~0x7fffffffu) >> n) (0x80000000u >> n) 

with value 2^(31-n) if 0 <= n < 32 (it's undefined behaviour if n outside range).

for other case, ouah's answer correct, when x = 0x80000000 int, ~0x8000000 = 0x7fffffff = int_max , int_max + 1 undefined behaviour signed integer overflow.

nevertheless, common behaviour wrap-around, , result of addition signed integer 0x80000000 , right-shifting of negative integers implementation-defined behaviour (6.5.7). common shifting sign-extension, yield result -2^(31-n), interpreted unsigned int value 2^32 - 2^(31-n) printf conversion specifier %x.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -