Question

what is a recommended way to perform addition and subtraction operations on Octal numbers? (My search results to date have yielded only conversions of octals, but not how to perform arithmetic operations on actual octals). My program would generate 2 octal values, then add or subtract these (randomly), and give the octal total.

eg.

 5 Octal + 3 Octal = 10 Octal;
 12 Octal - 3 Octal = 7 Octal;

I have tried using:

Integer.parseInt(int, 8), 

but I am not clear on how to construct for the above results. I have the rest of the programming working, I'm just stuck on the octal calculations. I am a brand new programming student, working my way through the "Art and Science of Java" textbook by Eric S. Roberts, and this is listed as a programming exercise (Chapter 7, Exercise 3).

Was it helpful?

Solution

You have a basic misunderstanding of the concept. Arithmetic is performed on numbers, not on octal numbers or decimal numbers or hexadecimal numbers.

The octal/decimal/hex aspect refers only to the written representation.

As you probably know, to write a literal octal value in the code, you prefix it with a leading zero. Similarly to write a hex value you prefix it with 0x.

To print a value in octal, use Integer.toOctalString(int).

To parse a string and interpret it as an octal value, use Integer.parseInt(value, radix), and specify 8 as the radix.

For example, you two examples become:

int value1 = Integer.parseInt("5", 8);
int value2 = Integer.parseInt("3", 8);

int result = value1 + value2;
System.out.println(Integer.toOctalString(result));

and

int value1 = Integer.parseInt("12", 8);
int value2 = Integer.parseInt("3", 8);

int result = value1 - value2;
System.out.println(Integer.toOctalString(result));

OTHER TIPS

You can use Integer.toOctalString(int) method to get octal representation of a number, if you meant that:

System.out.println(Integer.toOctalString(012 - 03));  // 7
System.out.println(Integer.toOctalString(05 + 03));   // 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top