SOURCE: java code for adding octal, hexadecimal subtracting binary,
Hello desireejane,
One method is to do the following
public static long octalToDecimal(String octal) throws NumberFormatException {
// Initialize result to 0
long res = 0;
// Do not continue on an empty string
if (octal.isEmpty()) {
throw new NumberFormatException("Empty string is not an octal number");
}
// Consider each digit in the string
for (int i = 0; i < octal.length(); i++) {
// Get the nth char from the right (first = 0)
char n = octal.charAt(octal.length() - (i+1));
int f = (int) n - 48;
// Check if it's a valid bit
if (f < 0 || f > 7) {
// And if not, die horribly
throw new NumberFormatException("Not an octal number");
} else {
// Only add the value if it's a 1
res += f*Math.round(Math.pow(2.0, (3*i)));
}
}
return res;
}
In the octal system each place is a power of eight. For example:
By performing the calculation above in the familiar decimal system we see why 112 in octal is equal to 64+8+2 = 74 in decimal.72 views
Usually answered in minutes!
×