|
| 1 | +/** |
| 2 | + + * Converts any Hexadecimal Number to Octal |
| 3 | + + * |
| 4 | + + * @author Tanmay Joshi |
| 5 | + + * |
| 6 | + + */ |
| 7 | +importjava.util.Scanner; |
| 8 | + |
| 9 | +publicclassHexToOct |
| 10 | +{ |
| 11 | +/** |
| 12 | + + * This method converts a Hexadecimal number to |
| 13 | + + * a decimal number |
| 14 | + + * |
| 15 | + + * @param The Hexadecimal Number |
| 16 | + + * @return The Decimal number |
| 17 | + + */ |
| 18 | +publicstaticinthex2decimal(Strings) |
| 19 | + { |
| 20 | +Stringstr ="0123456789ABCDEF"; |
| 21 | +s =s.toUpperCase(); |
| 22 | +intval =0; |
| 23 | +for (inti =0;i <s.length();i++) |
| 24 | + { |
| 25 | +chara =s.charAt(i); |
| 26 | +intn =str.indexOf(a); |
| 27 | +val =16*val +n; |
| 28 | + } |
| 29 | +returnval; |
| 30 | + } |
| 31 | + |
| 32 | +/** |
| 33 | + + * This method converts a Decimal number to |
| 34 | + + * a octal number |
| 35 | + + * |
| 36 | + + * @param The Decimal Number |
| 37 | + + * @return The Octal number |
| 38 | + + */ |
| 39 | +publicstaticintdecimal2octal(intq) |
| 40 | +{ |
| 41 | +intnow; |
| 42 | +inti=1; |
| 43 | +intoctnum=0; |
| 44 | +while(q>0) |
| 45 | +{ |
| 46 | +now=q%8; |
| 47 | +octnum=(now*(int)(Math.pow(10,i)))+octnum; |
| 48 | +q/=8; |
| 49 | +i++; |
| 50 | +} |
| 51 | +octnum/=10; |
| 52 | +returnoctnum; |
| 53 | +} |
| 54 | +// Main method that gets the hex input from user and converts it into octal. |
| 55 | +publicstaticvoidmain(Stringargs[]) |
| 56 | + { |
| 57 | +Stringhexadecnum; |
| 58 | +intdecnum,octalnum; |
| 59 | +Scannerscan =newScanner(System.in); |
| 60 | + |
| 61 | +System.out.print("Enter Hexadecimal Number : "); |
| 62 | +hexadecnum =scan.nextLine(); |
| 63 | + |
| 64 | +// first convert hexadecimal to decimal |
| 65 | + |
| 66 | +decnum =hex2decimal(hexadecnum);//Pass the string to the hex2decimal function and get the decimal form in variable decnum |
| 67 | + |
| 68 | +// convert decimal to octal |
| 69 | +octalnum=decimal2octal(decnum); |
| 70 | +System.out.println("Number in octal: "+octalnum); |
| 71 | + |
| 72 | + |
| 73 | + } |
| 74 | +} |