xonecas.io
92
Nu

NumberConversion / files

NumberConversion / NumberConversion.java

1.9 KB
1// sean caetano martin
2// seancaetanomartin@gmail.com
3// cis 255 hy
4// NumberConversion
5// converts decimal numbers to binary, hex, octal.
6// assign 1
7// Wednesday, February 02 2011
8
9public class NumberConversion {
10
11   public static String convertToBinary (int decimal) {
12
13      // local variables
14      int remainder = 0;
15      String binary = "";
16
17      // division by 2 with remainder
18      // continue while the quotient != 0
19      do {
20
21         // save the integer value of the remiander (1 || 0)
22         remainder = decimal % 2;
23         // divide the number by 2 and capture the quotient
24         decimal = decimal / 2;
25
26         // build our binary number in reverse order
27         binary = remainder + binary; 
28
29      } while (decimal != 0);
30
31      // return our binary number
32      return binary;
33
34   }
35
36   public static String convertToOctal (int decimal) {
37   
38      // local variables
39      int remainder = 0;
40      String octal = "";
41
42      // division by 8 with remainder
43      // while the quotient != 0
44      do {
45
46         // save the integer value of the remainder
47         remainder = decimal % 8;
48         // save the quotient
49         decimal = decimal / 8;
50
51         // build the octal number
52         octal = remainder + octal;
53
54      } while (decimal != 0);
55
56      // return the octal number
57      return octal;
58   }
59
60   public static String convertToHexadecimal (int decimal) {
61   
62      // local variables
63      int remainder = 0;
64      String hex = "";
65      String hexValues = "0123456789ABCDEF";
66
67      // division by 16 with remainder
68      // while the quotient != 0
69      do {
70
71         // save the integer value of the remainder
72         remainder = decimal % 16;
73         // save the quotient
74         decimal = decimal / 16;
75
76         // build the hex number
77         hex = hexValues.charAt(remainder) + hex;
78
79      } while (decimal != 0);
80
81      // return the hex number
82      return hex;
83   }
84}