Peanutcalota Peanutcalota - 2 months ago 9
Java Question

Why isn't my Bit String to Hex String code printing the result?

I am trying to print the result of a bit string to hex string conversion but it prints nothing. In other words 000110011101 should print "19d" are my temp variables the issue?

Thanks in advance for any assistance, this is my code:

public static void BinaryToHex() {
Scanner scanner = new Scanner(System.in);
String bitString = "";
String hexString = "";

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" };

System.out.println("Enter a bit string: ");
bitString = scanner.next();

for (int i = 0; i < bitString.length(); i++) {
char temp = bitString.charAt(i);
String temp2 = "" + temp + "";
for (int j = 0; j < binary.length; j++) {
if (temp2.equalsIgnoreCase(binary[j])) {
hexString = hexString + hex[j];
}
}
}

System.out.print("The equivalent hex string is ");
System.out.println(hexString);
}

Answer
for (int i = 0; i < bitString.length(); i++) {
        char temp = bitString.charAt(i);
        String temp2 = "" + temp + "";
        for (int j = 0; j < binary.length; j++) {
            if (temp2.equalsIgnoreCase(binary[j])) {
                hexString = hexString + hex[j];
            }
        }
    }

In this loop you are trying to take one character of a bitString at a time and compare it with the input of binary[] array which has all input of length 4. So basically you are trying to comparing 1 length element with 4 length element which is never gonna be true.

So HexString will never get changed and it will print same as you have initialized it.So you are getting nothing while executing the code.

So you can have a substring of bitString having 4 lengths and store it in temp2 then this code will work and for every 4 bits there is a HexCharacter so you can't make 1 bit number into binary number.

So as per your logic ,bitString length should be of multiples of 4 otherwise it won't give corresponding hex character from hex array.

So replace the for loop in you code with this.

if(bitString.length()%4!=0)
    System.out.println("Please Enter Valid Input.");
else
{
    for (int i = 0; i < bitString.length()/4; i++) 
    {
        String temp2 = bitString.substring(4*i,4*(i+1));
        for (int j = 0; j < binary.length; j++)
            {
            if (temp2.equalsIgnoreCase(binary[j]))
                {
                hexString = hexString + hex[j];
            }
        }
    }
    System.out.print("The equivalent hex string is ");
    System.out.println(hexString);
}
Comments