One algorithm for converting a positive decimal to two's complement
binary:
Convert decimal X10 > 0 to two-'s complement
binary: (dsignd30...d7d6d5d4d3d2d1d0)2
1) Initially set di = 0 for all i
2) What is the largest power of 2 <= X10? Call
is 2k.
3) Set dk = 1
4) Set X'10 = X10 % 2k
5) If X'10 = 0, stop, otherwise repeat steps 2-4 with X'10
Example: Convert 53010 to two's complement binary.
29 = 512 <= 530, so 530 % 29 = 18, set d9
= 1
24 = 16 <= 18, so 18 % 24 = 2, set d4
= 1
21 = 2 <= 2, so 2 % 21 = 0, set d1
= 1
stop
So we have: 53010 = 0000 0000 0000 0000 0000 0010 0001 0010
A similar algorithm for converting a negative decimal to two's complement
binary:
Convert decimal Y10 < 0 to to two's complement
binary: (dsignd30...d7d6d5d4d3d2d1d0)2
1) Set Y'10 = | Y10 |
2) Set Y''10 = Y'10 - 1
3) Find the two's complement of Y''10 using the algorithm for
positive decimals, call it D2
4) Flip the bits of D2, that is switch 1's to 0's
and 0's to 1's
Example: Convert -102310 o two's complement binary.
1023 = | -1023 |
1022 = 1023 - 1
29 = 512 <= 1022, so 1022 % 29 = 510, set
d9 = 1
28 = 256 <= 510, so 510 % 28 = 254, set d8
= 1
27 = 128 <= 254, so 254 % 27 = 126, set d7
= 1
26 = 64 <= 126, so 126 % 26 = 62, set d6
= 1
25 = 32 <= 62, so 62 % 25 = 30, set d5
= 1
24 = 16 <= 30, so 30 % 24 = 14, set d4
= 1
23 = 8 <= 14, so 14 % 23 = 6, set d3
= 1
22 = 4 <= 6, so 6 % 22 = 2, set d2
= 1
21 = 2 <= 2, so 2 % 21 = 0, set d1
= 1
stop
So we have 102210 = 0000 0000 0000 0000 0000 0011 1111 1110
Now flip the bits to get -102310 = 1111 1111 1111 1111 1111
1100 0000 0001
note: For binary to hex conversions, just use the table. |