0

Below I have a method named 'hextoBinary' that returns a hexadecimal to binary conversion through type void.

In order for me to continue with my program I need a conversion from hex to binary method that returns and int so I can convert that binary int into a decimal with my 'hextoDecimal' method.

Can anybody help me or guide me on what approach to take, i've been stuck on this for a while now. i am limited to doing this manually instead of using parse or java automatic conversions.

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class Main
{
    static void hexToBinary(char hexdec[])
    {
        for (char c: hexdec)
        {
            switch (c)
            {
                case '0':
                    System.out.print("0000");
                    break;
                case '1':
                    System.out.print("0001");
                    break;
                case '2':
                    System.out.print("0010");
                    break;
                case '3':
                    System.out.print("0011");
                    break;
                case '4':
                    System.out.print("0100");
                    break;
                case '5':
                    System.out.print("0101");
                    break;
                case '6':
                    System.out.print("0110");
                    break;
                case '7':
                    System.out.print("0111");
                    break;
                case '8':
                    System.out.print("1000");
                    break;
                case '9':
                    System.out.print("1001");
                    break;
                case 'A':
                    System.out.print("1010");
                    break;
                case 'B':
                    System.out.print("1011");
                    break;
                case 'C':
                    System.out.print("1100");
                    break;
                case 'D':
                    System.out.print("1101");
                    break;
                case 'E':
                    System.out.print("1110");
                    break;
                case 'F':
                    System.out.print("1111");
                    break;
                default:
                    System.out.print("\nInvalid hexadecimal digit " + hexdec[c]);
            }
        }
    }

    public static int hextoDecimal(int n)
    {
        int decimal = 0, p = 0;
        while(n != 0)
        {
            decimal += ((n % 10) * Math.pow(2,p));
            n = n / 10;
            p++;
        }
        return decimal;
    }

    public static void main(String[] args) throws IOException
    {
        Scanner sc = new Scanner(new File("RAMerrors8x4c"));
        ArrayList<String> hexValues = new ArrayList<>();

        while(sc.hasNext())
        {
            hexValues.add(sc.nextLine());
        }

        hexToBinary(hexValues.get(0).toCharArray());
    }
}

2 Answers 2

0

This code is based on some that came from here but that link no longer seems to be active. Anyway, from a hex string you can get an int like this:

int hexToDecimal(String s){
  int result = 0;
  int digit = 0;
  for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c >= '0' && c <= '9')
       digit = c - '0';
    else 
      if (c >= 'A' && c <= 'F')
        digit = 10 + c - 'A';
      else 
        inputError(s);
    result = 16 * result + digit;
  }
  return result
}
Sign up to request clarification or add additional context in comments.

1 Comment

sorry, I didn't read the question properly first time around. Nevertheless perhaps the code above might help because it can be modified to convert as you can call Integer.toBinaryString on the result, or indeed on the result from your existing hextoDecimal function.
0

I modified your code a little.

a. In your code only the first hex was printed.

Change:

  • call hexToBinary for every hex String.

b. the binary value was discarded after printing, so it couldn't be reused.

Change:

  • Changed returntype of hexToBinary from void to String and returned the binary value calculated.

  • To be able to return a String I add the peaces(nibbles) of the hex/binary to a String in every switch(case) clause.(a Stringbuilder might be better than a String - you can additionally improve that)

  • in the main: additionally collect all the returned binary values in a arraylist called "binaryValues" in order to have them for the next step.

With the above (little) changes I now have all the binary values that had already been calculated.

So I am able to simply use them in a binaryToDecimal method which just sums up the binary values weighted by their position.

Why not do it again? Because youd need to convert the A-F to numbers what your hexToBinary already did. So storing the values saves you doing that step again. I have a feeling that is what your teacher had in mind when he/she combined the tasks like this.

The resulting code is:

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class Main
{
     static String hexToBinary(char hexdec[]) {
            String hex = "";
            for (char c : hexdec) {
                switch (c) {
                    case '0':
                        System.out.print("0000");
                        hex += "0000";
                        break;
                    case '1':
                        System.out.print("0001");
                        hex += "0001";
                        break;
                    case '2':
                        System.out.print("0010");
                        hex += "0010";
                        break;
                    case '3':
                        System.out.print("0011");
                        hex += "0011";
                        break;
                    case '4':
                        System.out.print("0100");
                        hex += "0100";
                        break;
                    case '5':
                        System.out.print("0101");
                        hex += "0101";
                        break;
                    case '6':
                        System.out.print("0110");
                        hex += "0110";
                        break;
                    case '7':
                        System.out.print("0111");
                        hex += "0111";
                        break;
                    case '8':
                        System.out.print("1000");
                        hex += "1000";
                        break;
                    case '9':
                        System.out.print("1001");
                        hex += "1001";
                        break;
                    case 'A':
                        System.out.print("1010");
                        hex += "1110";
                        break;
                    case 'B':
                        System.out.print("1011");
                        hex += "1111";
                        break;
                    case 'C':
                        System.out.print("1100");
                        hex += "1100";
                        break;
                    case 'D':
                        System.out.print("1101");
                        hex += "1110";
                        break;
                    case 'E':
                        System.out.print("1110");
                        hex += "1110";
                        break;
                    case 'F':
                        hex += "1111";
                        System.out.print("1111");
                        break;
                    default:
                        System.out.print("\nInvalid hexadecimal digit " + hexdec[c]);
                }
            }
            System.out.println();
            return hex;
        }

        public static int binaryToDecimal(String binary) {
            int decimal = 0;
            for (int i = 1; i < binary.length()-1; i++) {
                    decimal += Math.pow(2, i-1) * (binary.charAt(binary.length()-i) - '0');
            }
            return decimal;
        }

        public static void main(String[] args) throws IOException {
            Scanner sc = new Scanner(new File("RAMerrors8x4c"));
            ArrayList<String> hexValues = new ArrayList<>();
            ArrayList<String> binaryValues = new ArrayList<>();
            while (sc.hasNext()) {
                hexValues.add(sc.nextLine());
            }
            for (String hex : hexValues) {
                String binary = hexToBinary(hex.toCharArray());
                binaryValues.add(binary);
                System.out.println(binary);
            }
            for (String binary : binaryValues) {
                int decimal = binaryToDecimal(binary);
                System.out.println(decimal);
            }
        }
    }
}

Besides using a Stringbuilder another idea could be to do all the printing of the binary values in the main. The hexToBinary returns the String - so you can print it in the loop - if you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.