1

I'm still newbie in java I have code but I'm still confused how does it works

so Anyone could explain to me how my code works in converting binary to hexadecimal? I'm a little bit confuse on the nested for loop part so please help me to understand the logic here

heres my code:

import java.io.*;

public class arrays {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(
                System.in));
        // Binary Storage
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String[] binary = { "0000", "0001", "0010", "0011", "0100", "0101",
                "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101",
                "1110", "1111" };
        // For User!, input a value:
        System.out.print("Input your Hex Number here : ");
        String userInput = input.readLine();
        String result = "";

        for (int i = 0; i < userInput.length(); i++) {
            /* used for separating the value */
            char temp = userInput.charAt(i);
            String temp2 = "" + temp + "";
            for (int j = 0; j < hex.length; j++) {
                if (temp2.equalsIgnoreCase(hex[j])) {
                    result = result + "\n" + temp + "- " + binary[j];
                }
            }
        }

        //Main output
        System.out.println("THE BINARY OF " + userInput + ":" + result);


    }
}
repsajznav
  • 61
  • 1
  • 8
  • Does this code work? –  Sep 24 '14 at 21:04
  • @nikpon Yes, but it's poor design. Keeping data in multiple arrays and relying on the index being to same to convert between them is a Bad Idea. – azurefrog Sep 24 '14 at 21:06
  • If the comment `used for separating the value` said `inspect each character in turn`, would that help you? – Andrew Morton Sep 24 '14 at 21:08
  • I suggest you step through your code in the debug in your IDE. This will allow you to see exactly what each line of code is doing. – Peter Lawrey Sep 24 '14 at 21:25
  • oh thank you for answering my question quickly.. @azurefrog Why its in poor design? – repsajznav Sep 24 '14 at 21:30
  • Because it's so easy for them to get out of sync. You are relying on both arrays to never be modified, unless both are modified in the exact same way. It's much better when dealing with compound information to make an object which holds compound data, and make an array of that object. – azurefrog Sep 24 '14 at 21:35
  • Thank you but it's even harder for me to understand it well .. BTW This is our project and I saw that everyone using that built it converter , so i decided to create a unique one.. so i can use our lesson which is Array and looping ... I just need to know what is the purpose of each code in my nested for loop – repsajznav Sep 24 '14 at 21:40
  • @nem hey dude . im very thankful for your comment and it really helps my project and sorry for a late feedback , So my question is , is this hashmap code that you wrote is better than my code? I mean what is the problem of my code and can u explain why it's better than mine..Thank you – repsajznav Sep 30 '14 at 12:36
  • @JasperVanzRecitas you are welcome sir. Yes, the hashmap version is better because, first of all, it looks cleaner. Secondly, it finds the value faster than your code because it doesn't need the inner loop. You just connect hex value to a binary value in a map and then you can get it in constant time and you don't have to loop through an array to find it. I explained this in my answer as well. I also showed you how to do everything you need in one line of code :). Hope this helps – nem035 Sep 30 '14 at 13:59
  • @nem you're the best dude. Thanks for keeping answering my questions: sir , im very sorry if asked to much and abusive .. sorry but i want to learn more: i wanna test the last code that you provided to me which is the Built it java binary coverter.. i have a problem if the userinputs int 5, it only displays 101 and if i type 1 it only displays 1 too, but if i type in String it gives the right conversion ... So you could you explain me why is this happening? BTW the code that i'm talking about is the last code that you provided to me thanks – repsajznav Sep 30 '14 at 14:26
  • @JasperVanzRecitas no problem, we are all always learning :). You should google the methods I gave you there and read more about them but the reason it shows "101" for "5" is that it strips all the trailing zeros since "0101" is the same as "00000101" and same as "101". – nem035 Sep 30 '14 at 16:37

1 Answers1

0

Your code does work but it is inefficient. There's also some room for simplification.

First of all, what you can do to make your program more efficient, is build a HashMap<Character, String> of hex characters to binary strings:

HashMap<Character, String> map = new HashMap<Character, String>();
map.put("0", "0000");
map.put("1", "0001");
// ...
map.put("F", "1111");

Now you don't need the inner for loop and comparing values will be much faster since map lookup by key is technically constant time.

Further more, instead of using the + symbol for concatenating strings, use a StringBuilder to build your result and speed things up a bit (read why here).

Also for readability purposes, you should probably use more-significant variable names instead of temp and temp2.

Here how your code can look (full running sample link):

    // ...
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < userInput.length(); i++) {
            /* used for separating the value */
            char hexVal = userInput.charAt(i);
            String binary = map.get(hexVal);
            result.append(binary);
    }

    //Main output
    System.out.println("THE BINARY OF " + userInput + ":" + result.toString());

In general, these types of conversions work by converting to decimal value first and then to correct value, so:

binary -> decimal -> hex
hex -> decimal -> binary

Java already has methods that can help you do just that.

This is how you can convert from a String containing a hexadecimal number to a String containing a binary value of that number:

String hex = "f";                                // 15 in hex
int decimal = Integer.parseInt(hex, 16);         // this gives 15 in decimal (converts from base 16 to base 10)
String binary = Integer.toBinaryString(decimal); // this gives "1111"
System.out.println(binary);                      // this prints "1111"

This is how you can convert from a String containing a binary number to a String containing a hexadecimal value of that number:

String binary = "1111";                    // 15 in decimal
int decimal = Integer.parseInt(binary, 2); // this gives 15 in decimal (converts from base 2 to base 10)
String hex = Integer.toHexString(decimal); // this gives "f"
System.out.println(hex);                   // this prints "f"

Now, for your program, you can just use these methods, you don't need String[] hex and String[] binary arrays or the for loop:

public static void main(String[] args) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(
            System.in));

    // For User!, input a value:
    System.out.print("Input your Hex Number here : ");
    String userInput = input.readLine();

    // conversion from hex to binary in one line, ain't that awesome :)
    String result = Integer.toBinaryString(Integer.parseInt(userInput, 16));

    //Main output
    System.out.println("THE BINARY OF " + userInput + ":" + result);

}

Now, of course, you have take care of invalid input with either catching exceptions thrown by Integer.parseInt and Integer.toBinaryString or making you own function that will check if input is a valid hex number.

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99