I am to write a program that converts either binary, hex or octal to decimal. We are to use methods for the first time (Not a problem). I have written almost all of the code but the conversion. We can't use int.toDecimal or any shortcut. All must be long coded so that we learn something from the process.

I have looked for the past 3 days trying to find the answer to how this should be accomplished and have found nothing.

My question is how to take an input of either an integer or string and output it in one of the three. I know the formulas but I cannot figure out how to turn them into a working code. For instance: octal to decimal would ask for the number to be counted and then the powers of 8 adjusted accordingly: number = 765 so (7x8^2)+(6x8^1)+(5x8^0)
then it would be added and output in decimal form.

I need to figure out how to do this sort of thing with each and account for either input of any number be it hex or binary. Any help would be greatly appreciated.

Thanks in advance,
24x24

Recommended Answers

All 23 Replies

You are going to have to ask the user for 3 different things.
1. What kind of value are they entering (have them enter a char, ex. b for binary, d for decimal, h for hex)
2. What kind of value do they want to convert to.
3. The actual value of the number to be converted.

Once you have gotten an answer for the 3 questions above, you can
use if/else statements to call the right methods and deliver the right answer.

It would probably be best to read in the users number as a String, and parse the
string as needed.

I am to write a program that converts either binary, hex or octal to decimal. We are to use methods for the first time (Not a problem). I have written almost all of the code but the conversion. We can't use int.toDecimal or any shortcut. All must be long coded so that we learn something from the process.

I have looked for the past 3 days trying to find the answer to how this should be accomplished and have found nothing.

My question is how to take an input of either an integer or string and output it in one of the three. I know the formulas but I cannot figure out how to turn them into a working code. For instance: octal to decimal would ask for the number to be counted and then the powers of 8 adjusted accordingly: number = 765 so (7x8^2)+(6x8^1)+(5x8^0)
then it would be added and output in decimal form.

I need to figure out how to do this sort of thing with each and account for either input of any number be it hex or binary. Any help would be greatly appreciated.

Thanks in advance,
24x24

Mattox is correct; But to be more specific, look into the Scanner class to get User input, just incase you dont know how to get user input.
ex. Scanner sc= new Scanner(System.in);
String strinInput= sc.next();

I already have all of that written like I stated above, the problem I am having is in the conversion itself. Once they enter the conversion type and then enter the number to be converted I need to figure out how to have to program read the string and count how many characters it has (lets say charCount), change the string into an integer (numberIn), apply the number that was counted to the equation so that we have versatile entry possibilities (if numberIn is 765 than (7x8^2)+(6x8^1)+(5x8^0) or if numberIn is 8 than (8x8^0), and output the answer in decimal. I understand the equations for each and I know they can be done with the string.toDecimal but I can't use those. Therefore I have to figure out how to do all of this. I tried to use intCount figuring that might work but being a string and having to account fro hex input I am at a loss there. Even if I did get that to work would I just take charCount and loop until j applied to math.pow increments to equal it or would I have to go the reverse? Thanks for the help guys. I hope I'm on the right track but searching has done nothing but reveal the easy way out (which is not allowed).

Im still struggling with this one. I went to the help room on campus and the guy working in there told me it wasn't his responsibility to help me. I didn't want him to give me the answer, just a clue as to where to begin at least. Anyway, any thoughts? Any input would be greatly appreciated.

This is what I have so far:

/*
 * Program needs to take a number input of hex, octal or binary and convert it to decimal
 */
package converter;

/**
 *
 * @author 24x24
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //declare variables
        int number = 0;

        Scanner keyboard = new Scanner(System.in); //create a Scanner object

        System.out.print("Enter the conversion type (Binary, Octal, Hex): ");
        String convString = keyboard.nextLine().toUpperCase(); //This will take an input from lower case to upper case
        if (convString.equals("OCTAL")) {
            System.out.print("Enter the number to be converted: ");
            number = keyboard.nextInt();
            //CALL OCTAL METHOD HERE

        } else {
            System.out.println("Wrong Conversion Type.");
        }



        if (convString.equals("BINARY")) {
            System.out.print("Enter the number to be converted: ");
            number = keyboard.nextInt();
            //CALL BINARY METHOD HERE

        } else {
            System.out.println("Wrong Conversion Type.");
        }


        if (convString.equals("HEX")) {
            System.out.print("Enter the number to be converted: ");
            number = keyboard.nextInt();
            //CALL HEX METHOD HERE

        } else {
            System.out.println("Wrong Conversion Type.");
        }
    }//end of main method

    /**
     * octal method
     * explain crap here
     */
    public static int octal (int number){
        int result;
       //this is where the formula for the octal conversion would go if i knew how to code it in without using toDecimal 

        return result;
    }

}//end of main class

I didn't include the binary or hex because the only difference in the three is that instead of (nx8^0) its x2 or x16 accordingly. No point in making giant threads.

Ok so this is what I have for binary conversion:

/**
     * binary method
     * explain crap here
     */

    public static long toDecimal(String binary)
{
long decimal=0L;
for (int i = 0, n = binary.length(); i < n; i++)
  {
  if ( binary.charAt(i) == '1' )
    decimal++;
  if ( i != n-1 )
    decimal*=2L;
  }
return decimal;
}//End of Binary Method

and it goes into an endless loop. No idea why. I'll keep trying. Hopefully i'll get it figured out but some help would really be appreciated.

Ok made some changes to a lot of the code so I'm going to post the whole thing. I got the binary portion to work, now I need to get the octal to work. Then the hex. The hex I foresee being an issue due to possible need for letter conversion. Not sure but I will cross that bridge when I get there.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package converter;

/**
 *
 * @author 24x24
 */
import java.util.Scanner;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //declare variables
        int number = 0;

        Scanner keyboard = new Scanner(System.in); //create a Scanner object

        System.out.print("Enter the conversion type (Binary, Octal, Hex): ");
        String convString = keyboard.nextLine().toUpperCase(); //This will take an input from lower case to upper case

        if (convString.equals("OCTAL")) {
            System.out.print("Enter the number to be converted: ");
            String octalString = keyboard.nextLine();

            long decimal = fromOctal(octalString); //CALL BINARY METHOD HERE
            System.out.print(decimal);
            System.out.println("");
            //CALL OCTAL METHOD HERE
        } else if (convString.equals("BINARY")) {
            System.out.print("Enter the number to be converted: ");
            String binaryString = keyboard.nextLine();

            long decimal = fromBinary(binaryString); //CALL BINARY METHOD HERE
            System.out.print(decimal);
            System.out.println("");

        } else if (convString.equals("HEX")) {
            System.out.print("Enter the number to be converted: ");
            number = keyboard.nextInt();
            //CALL HEX METHOD HERE
        } else {
            System.out.println("Wrong Conversion Type.");
        }
    }//end of main method

    /**
     * binary method
     * explain method here
     */
    public static long fromBinary(String binaryString) {
        long decimal = 0L;
        for (int i = 0, n = binaryString.length(); i < n; i++) {
            if (binaryString.charAt(i) == '1') {
                decimal++;
            }
            if (i != n - 1) {
                decimal *= 2L;
            }
        }
        return decimal;
    }//End of Binary Method

    /**
     * octal method
     * explain method here
     */
    public static long fromOctal(String octalString) {
        long decimal = 0L;
        for (int i = 0, n = octalString.length(); i < n; i++) {
            //logic for octal goes here. Trying to build off of what I used for binary, not sure if thatll work though
        }
        return decimal;
    } //End of Octal Method
    /**
     * hex method
     * explain method here
     *
    public static int hex (int number){
    int result;


    return result;
    }*/ //End of Hex Method
}//end of main class

To convert from base N to base ten:

start your accumulator variable ("decimal" in your program) at zero
start at the least significant (rightmost) digit
For each digit, the decimal value is (digit * (N^offset)) where offset is the number of places to the left of the decimal point. (starting from zero) This value gets added to your accumulator.

So, 0564 = 4* 8^0 + 6* 8^1 + 5*8^2 = 372 unless my mental arithmetic is off.

Binary, same thing: 101110100 = 0 +0 + 4+ 0+16+32+64+0+256 = 372, so it's probably right. Notice, by the way 101 110 100 - each triplet makes one digit of the octal string, this helps you with your mental math.

This might help a little. Since you're bringing in the number to convert as a String, you can count back from String.length()-1 to zero in your for loop, or it might be easier to write it as a while loop, either way you have to keep track of your offset so you can raise to the correct power.

I don't know what you're trying to do in your fromBinary, but it's not making much sense to me, so I won't try to correct it.

Thanks for the reply. My binary method is doing essentially what you described. it takes i and sets it to 0, finds the length of binaryString and then starts converting from the right side of the string and moving to the left by incrementing i. For some reason I cant get this logic to apply to the base 8 or 16 and I don't know what I'm doing wrong there. I took a break to go to a class and hopefully clear my head and Im going to try starting from the beginning with octal. I'll post results (hopefully)

Well, that's not exactly what it's doing. binaryString.charAt(0) is the leftmost character of the string. "987654321".charAt(0) == '9'

But I guess it works - looks awful funny, but it works
10100 = (((((((1)*2)+0)*2)+1)*2)+0)*2)+0)*2)= ((((2*2)+1)*2)*2) = 20

Not bad, but I think my way's easier. :)
Try doing your octal from right to left, as I described, and see if it works for you.
(If your way makes more sense to you, then you should think about learning some Lisp :) )

Well, that's not exactly what it's doing. binaryString.charAt(0) is the leftmost character of the string. "987654321".charAt(0) == '9'

But I guess it works - looks awful funny, but it works
10100 = (((((((1)*2)+0)*2)+1)*2)+0)*2)+0)*2)= ((((2*2)+1)*2)*2) = 20

Not bad, but I think my way's easier. :)
Try doing your octal from right to left, as I described, and see if it works for you.
(If your way makes more sense to you, then you should think about learning some Lisp :) )

I'm trying your way (I think). So far I am taking the amount of the string and applying it to j and using that times 8^i. From there it gets all messed up but I'm working on it. I think I need to figure out what to do with pow once it is the actual number instead of whats going on. Would I be better off to just add pow to the next outcome and if so how?
This is where I'm stuck:

public static long decimal(String octalString) {
        //Convert string to binaryString
        int decimal = 1;
        for (int i = 0, n = octalString.length(), j = octalString.charAt(i); i < n; i++) {

           
            double pow = j* Math.pow(8, i);

            decimal = (int)(decimal * pow);
        }
        return decimal;

And lisp? Isn't that some ancient language? Only reference I have ever seen made to lisp is on XKCD and I didn't care enough to look it up at the time

Ok, I think I might be very close. As I was stepping through the debugger I realized my code was taking j from the string but declaring the value to be from the ASCII value so 4 was 52 and not 4 and then it multiplied by 8^i. So I need to find a way to convert the string but still claim one number at a time as j. Possible?
Slight revisions:

public static long decimal(String octalString) {
        //Convert string to int
        
        int decimal = 0;
        for (int i = 0, n = octalString.length(), j = octalString.charAt(i); i < n; i++) {

           
            double pow = j* Math.pow(8, i);

            decimal = (int) (pow + decimal);
            
        }
        return decimal;

Ok still trying. Some revisions seem to be yielding some promise. The only problem is that it only calculates the last number (92 it takes 2 and outputs 16 because 2x8^i is 16) then it stops. This is what I have:

public static long decimal(String octalString) {
        //Convert string to int

        int decimal = 0;
        int j = 1;
        //for (int i = 0, n = octalString.length(), j = octalString.charAt(i); i < n; i++) {
        for (int i = octalString.length()-1; i > 0; i--) {
            String k = octalString.substring(i,i+1);
            int l = Integer.parseInt(k);
            double pow = l* Math.pow(8, j);

            decimal += (int) (pow);
            j++;
        }
        return decimal;

This thing is due by midnight so I'm really trying. Thanks again for all the help

Standard idiom for convert char from ASCII to int (w/o library methods) is char value - '0'. That is, since '0' is the first integer mentioned in the ASCII table and they follow in sequence from there, whatever the ASCII value of '0' is, which you don't know and don't care at this point (48, if you ever do care) you know that '1'-that = 1. Ditto '2'-'0'=2 and so forth. That might help. Good catch on figuring out that it was using the ASCII value.

However, you're still reading left to right, which is going to mess you up.

(Edit: you caught that, good. )

if octalString = "0654", then octalString.getChar(0) = what?

commented: Very straight forward but didn't just give me the answer. Very good +1

Remember that your offset is from the right end of the String, so if i is the position in the string, then your offset grows as i shrinks. You're going to have to track the offset increasing from the least significant place - starts at 0, grows to length-1

(ie, 1000 = 10^3)

Ok I think I'm missing something fundamental here. I changed the code so that it would shift using what you suggested by subtracting '0'. I am getting closer but for some reason now it is yet again going from left to right. I have tried everything and each time it just goes with the leftmost number first. Then it seems to stay with that number. Not sure what I broke since I don't think I changed the order it should go in so I am assuming its something in there that is forcing it to the far left? Like one of the increments keeps it so far left that when I bring it up it is still to the very left. Does that even make sense?

public static long decimal(String octalString) {
        //Convert string to int
        int decimal = 0;
        int j = 0;
        for (int i = octalString.length() - 1, n = octalString.charAt(j); i >= 0; i--) {

            int number = n - '0';
            double power = number * Math.pow(8, i);
            j--;
            decimal += (int) (power);

        }
        return decimal;

Ok I've stepped through this a hundred different times. My issue lies with j. For some reason it is not changing no matter what I increment it to. It continues to grab the same character from the string every time. If I input 24 it goes through and grabs the 2 and then the code does what it should. Second time around instead of grabbing the 4 it grabs the 2 again. Everything else looks to be working properly. Any ideas as to how I should fix this? I have moved the n=charAt, Ive changed j to equal every number possible, Ive incremented and decremented j with different values. Im running out of ideas and time. Any help would be greatly appreciated!

I fixed the portion for the octal. All I did was pull the charAt portion out of the for loop and put it below. I don't know why this worked but here it is:

public static long decimal(String octalString) {
        //Convert string to int
        int decimal = 0;
        int j = 0;
        for (int i = octalString.length() - 1; i >= 0; i--, j++) {
        char n = octalString.charAt(j);
            int number = n - '0';
            double power = number * Math.pow(8, i);
            
            decimal += (int) (power);

        }
        return decimal;

Now I have to do the hex, put in some faults and I'm done. Any ideas on how to add hex conversion to this? I need the code to pull letters and then multiply by that numbers hex value so A would be x10

Why that worked is that the initializer part of the loop only executes the first time through (imagine if you set i=0 each time you came to the top of the loop...)


For your hex portion, it's probably easiest to write a little helper method, hexDigitToDecimal, that accepts a char and returns an int. You can use similar character manipulation logic to determine the Right Thing To Do in that - if it's in the range '0'..'9' then do the same conversion as before. If it's in 'A'..'F' then you have to use the same logic, only ading a correcting factor (since 'A' is 10 and not 0).

You could do this as part of your hex conversion method, but you should get in the habit of turning stuff like this into helper methods - it really helps you see what's happening in your code.

Well before I read what you had just posted, I went the long way around because I seem to like doing things the hard way. I am assuming by helper you mean basically cut all the crap out that I just wrote, throw an if/else in and call the hexTo method?

public static int fromHex(String hexString) {
        //Convert string to int
       int decimal = 0;
        int j = 0;
        for (int i = hexString.length() - 1; i >= 0; i--, j++) {
        char n = hexString.charAt(j);
        if (n == 'A' || n== 'a'){
            n='A'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else if (n == 'B' || n== 'b'){
            n='B'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else if (n == 'C' || n== 'c'){
            n='C'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else if (n == 'D' || n== 'd'){
            n='D'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else if (n == 'E' || n== 'e'){
            n='E'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else if (n == 'F' || n== 'f'){
            n='F'-55;
            int number = n;
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }
        else{
            int number = n - '0';
            double power = number * Math.pow(16, i);

            decimal += (int) (power);
        }

        }
        return decimal;

I got all of the faults written, all of the conversions work, everything is commented and pretty. Thanks for all of your help. Im actually understanding whats going on for the most part which is more than I can say for when the prof explains it. Thanks again. Greatly appreciated!

Glad to help - it's always nice to see someone trying to understand what's going on, instead of just wanting their homework finished for them.

Keep it up, and you'll be walking people through these problems in six months.

As for your conversions... we'll talk about that another time. Let's just say, there's more than one way to do it. :)

Glad to help - it's always nice to see someone trying to understand what's going on, instead of just wanting their homework finished for them.

Keep it up, and you'll be walking people through these problems in six months.

As for your conversions... we'll talk about that another time. Let's just say, there's more than one way to do it. :)

Well I'd much rather have it explained so that I understand it the first time than have to come back many times asking somebody to help and they just write it for me. Teach a man to fish and all that. The conversions are crazy but I'm assuming that is how it was intended. They want us to understand and appreciate the libraries. I do understand the intent with teaching us in that manner and it works to an extent, but the understanding does have to be there somewhat in the first place. The teacher is more interested in telling stories of his time in the service than actually teaching and so I am very glad we have informative people on sites like this that are willing to take the time out of their day to help some future code gurus on their path to greatness. Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.