Question on Signed integer

M

M

Hi,

I was told that an Java int is a signed 32 bits integer and
ranged from -2^31 to 2^31 -1 (^: to the power of).

Then, I would like to know if -31 should be represented by:
(1) 10000000 00000000 00000000 00011111, or
(2) 11111111 11111111 11111111 11111111

(1) or (2)?

I think it's (2) because -31 >>> 5 yields 3
but I found no doc from java.sun.com relating to this.

Please let me have your comments or please
direct me to some websites for clarifications.

Thx
 
B

Boudewijn Dijkstra

M said:
Hi,

I was told that an Java int is a signed 32 bits integer and
ranged from -2^31 to 2^31 -1 (^: to the power of).
Correct.

Then, I would like to know if -31 should be represented by:
(1) 10000000 00000000 00000000 00011111, or
(2) 11111111 11111111 11111111 11111111

Both wrong. It is:
(3) 11111111 11111111 11111111 11100001

(1) in decimal would be -2147483617 (0x80000000 + 31)
(2) in decimal would be -1

Because the integer is so-called twos-complement.
This means that the equation
-x == ~x + 1
is true for all 2's-complement binary integers with a fixed number of bits.
(And where the '~'-operator represents bitwise NOT.)
I think it's (2) because -31 >>> 5 yields 3

I don't understand your reasoning. Can you elaborate, assuming that the
reasoning is still valid after my answer?
but I found no doc from java.sun.com relating to this.

The fact that integers are 2's-complement is explained here:
<http://java.sun.com/docs/books/vmspec/2nd-edition/html/Concepts.doc.html#19
511> (one link)
 
J

John B. Matthews

M said:
Hi,

I was told that an Java int is a signed 32 bits integer and
ranged from -2^31 to 2^31 -1 (^: to the power of).

Then, I would like to know if -31 should be represented by:
(1) 10000000 00000000 00000000 00011111, or
(2) 11111111 11111111 11111111 11111111

(1) or (2)?

I think it's (2) because -31 >>> 5 yields 3
but I found no doc from java.sun.com relating to this.

Please let me have your comments or please
direct me to some websites for clarifications.

Thx

11111111 11111111 11111111 11111111 = -1.
11111111 11111111 11111111 11100001 = -31.

http://www.evergreen.edu/biophysics/technotes/program/2s_comp.htm

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top