|
int x;
int main()
{
x = 35; // 35 = 100011 (bin) = 23 (hex)
}
|
If you compile this C program with this command:
gcc -c prog,c
|
and then dump the instruction in hex format with:
objdump -d prog.o
|
You will see this:
0000000000000000 <main>: 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp 4: c7 05 00 00 00 00 23 movl $0x23,0x0(%rip) b: 00 00 00 e: b8 00 00 00 00 mov $0x0,%eax 13: 5d pop %rbp 14: c3 retq |
I have highlighted the machine instruction that contains the 2s complement code for 35 (remember that it is a hex dump !)
You have to read the bytes in reverse order (explain later). The C compiler stored this 2s complement code in the program:
Hex: 00 00 00 23 = 00000000 00000000 00000000 00100011 |
x = -35; |
You will see the 2s complement code for -35
0000000000000000 <main>: 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp 4: c7 05 00 00 00 00 dd movl $0xffffffdd,0x0(%rip) b: ff ff ff e: b8 00 00 00 00 mov $0x0,%eax 13: 5d pop %rbp 14: c3 retq |
The 2s compl code generated by the C compiler is:
Hex: ff ff ff dd = 11111111 11111111 11111111 11011101 |
As you know (from "how to nagate 2s complement codes"), this 2s complement code represents −35
|
We have just learned about the 2s complement code that can be used to represent signed integer (= whole, not fractional) value in such a way that operations can be perform on them without considering the sign of the values.
(Remember the sign-magnitude representation had the problem when you add a negative value, you must perform a different operation (you had to subtract instead of add)).
So in this webpage, I like to show you that the int, short, and byte data types in Java uses the 2s complement code:
byte data type: uses an 8 bits 2s complement code short data type: uses an 16 bits 2s complement code int data type: uses an 32 bits 2s complement code |
I have written 3 Java programs that prints out the binary representation of the values stored inside a variable:
Demo directory: /home/cs255001/demo/java/
Program files: ShowByteAdd.java
ShowShortAdd.java
ShowIntAdd.java
|
These demo files can be copied; I will show them in class.
Sample run:
cheung@aruba> java ShowByteAdd
Enter a: 2
a = 2 ===> 2's complement repr = 00000010
Enter b: -1
b = -1 ===> 2's complement repr = 11111111 (In 2s complement, 11111111 represents -1 !!!)
a + b = 1
===> 2's complement repr = 00000001 (Computer can perform binary addition !!!)
=============================================
Overflow:
Enter a: 127
a = 127 ===> 2's complement repr = 01111111 (This is the largest postive number in 8 bits 2s compl)
Enter b: 1
b = 1 ===> 2's complement repr = 00000001
a + b = -128
===> 2's complement repr = 10000000 (0111111 + 00000001 = 10000000
The addition is correct !
BUT: the interpretation fails
We call this phenomenon: overflow)
=============================================
|
Here is some of the things you should notice when you run the demo:
|