M Hasan

Ranch Hand

Posts: 35

posted 1 year ago

I am reading a book and came across a code which I don't get. Please help:

My understanding is display mask = -2147483648 which is 10000000 00000000 00000000 00000000

and for loop 32th iteration input is = -2147483648 which is 10000000 00000000 00000000 00000000

Then the AND has to be ------------------------------------------- 10000000 00000000 00000000 00000000

But the code output is 00000000 00000000 00000000 00000001

Please clarify if someone out there knows how it is working. Please also give me some example if it is possible like how input -1 will behave.

My understanding is display mask = -2147483648 which is 10000000 00000000 00000000 00000000

and for loop 32th iteration input is = -2147483648 which is 10000000 00000000 00000000 00000000

Then the AND has to be ------------------------------------------- 10000000 00000000 00000000 00000000

But the code output is 00000000 00000000 00000000 00000001

Please clarify if someone out there knows how it is working. Please also give me some example if it is possible like how input -1 will behave.

posted 1 year ago

Something like

Then & the mask against the input to see if it's not zero.

0x80000000 is an int with the most significant bit (i.e. left-most bit) set to '1'.

In bits that would be: 10000000 00000000 00000000 00000000

mask >>>= 1 shifts the mask one bit to the right without sign extending the most significant bit.

Yours was starting at the least significant bit and shifting left by one bit.

Then & the mask against the input to see if it's not zero.

0x80000000 is an int with the most significant bit (i.e. left-most bit) set to '1'.

In bits that would be: 10000000 00000000 00000000 00000000

mask >>>= 1 shifts the mask one bit to the right without sign extending the most significant bit.

Yours was starting at the least significant bit and shifting left by one bit.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

M Hasan

Ranch Hand

Posts: 35

M Hasan

Ranch Hand

Posts: 35

M Hasan

Ranch Hand

Posts: 35

posted 1 year ago

Don't know where you got the -2147483648 from but the 000...00001 is the correct bit pattern for the input of "1"

The right most bit is 1, the next one to the left is 2, and the next is 4, etc..
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

M Hasan wrote:thanks Carey Brown but now it is giving the same result like my code which is

Please Enter Integer

1

The integer in Bit is :

-2147483648

00000000000000000000000000000001

I thought the answer is 10000000000000000000000000000000

Don't know where you got the -2147483648 from but the 000...00001 is the correct bit pattern for the input of "1"

The right most bit is 1, the next one to the left is 2, and the next is 4, etc..