1
//convert hexadecimal to binary using BigInt
public static String hexToBinary(String hexNumber)
{
    //BigInteger temp = new BigInteger(hexNumber, 16);
    //return temp.toString(2);
        String s = hexNumber;
        byte[] bytes = s.getBytes();
        StringBuilder binary = new StringBuilder();
        for (byte b : bytes)
        {
            int val = b;
            for (int i = 0; i < 8; i++)
            {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
        }
        System.out.println("'" + s + "' to binary: " + binary);
        return binary.toString();
}

String hexNumber is "0957" and the function returns "00110000 00111001 00110101 00110111"...I was expecting "0000 1001 0101 0111". Can someone identify what the problem is? Thanks.

4
  • 1
    Each hex character is 4 bits, but your inner loop goes from 0 to 8. That's why you get 8 characters for each hex char. Commented Apr 5, 2016 at 12:53
  • Is this for a school project that requires you to not use Java's functions? Commented Apr 5, 2016 at 13:01
  • @JoseCifuentes It's not a school project, I can use Java functions... Commented Apr 5, 2016 at 13:14
  • Ok, then I posted two ways of doing it, there's a lot of Java functions to help with that. Commented Apr 5, 2016 at 13:37

3 Answers 3

4

You are converting the numeric values of the characters '0','9','5','7' to binary, instead of converting the actual number. For example, the numeric value of '0' is 48, which is why the first byte you print is 00110000.

You need to subtract 48 (or '0') from each character before converting it to bits, and also remember that each hex character can be represented by 4 bits, but your loop prints 8 bits for each character. Actually that would only work if your input doesn't have the hex digits A to F (from the hex digits A to F you have to subtract ('A' - 10) in order to convert them to the numbers 10 to 15).

Here's one way to do it (still missing handling of digits 'A' to 'F', but works for your sample input) :

    byte[] bytes = s.getBytes();
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes)
    {
        int val = b - '0';
        val <<= 4;
        for (int i = 0; i < 4; i++)
        {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
        }
        binary.append(' ');
    }
    System.out.println("'" + s + "' to binary: " + binary);

Output :

'0957' to binary: 0000 1001 0101 0111 
Sign up to request clarification or add additional context in comments.

2 Comments

How would I detect if A-F is in the digit? I have take your suggestions into account so far.
@daemoner119 well, instead of iterating over s.getBytes(), iterate over s.toCharArray(), and for each character, check whether it is between '0' to '9' or between 'A' and 'F', and make the proper subtraction accordingly.
1

Here are two ways of doing it:

public class Snippet {
    public static String hexToBinary1(String hexNumber)
    {
        int v = Integer.parseInt(hexNumber, 16);
        String s = Integer.toString(v, 2); 
        int pad = hexNumber.length()*4-s.length();
        for (int i=0; i<pad; i++) {
            s="0"+s;
        }
        return s;
    }

    public static String hexToBinary2(String hexNum) {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<hexNum.length(); i++) {
            int v = Character.digit(hexNum.charAt(i), 16);
            String padded = String.format("%4s",  Integer.toString(v, 2)).replace(' ', '0');
            sb.append(padded);
        }
        return sb.toString();
    }

    public static void main(String[] arjgs) {
        System.out.println(hexToBinary1("0957"));
        System.out.println(hexToBinary2("0957"));
    }
}

Both will print out 0000100101010111.

Comments

0
String char  binary number
"0" → 0x0030 → 0000 0000 0011 0000
"1" → 0x0031 → 0000 0000 0011 0001
"2" → 0x0032 → 0000 0000 0011 0010
 :
"9" → 0x0039 → 0000 0000 0011 1001
"A" → 0x0041 → 0000 0000 0100 0001
"B" → 0x0042 → 0000 0000 0100 0010
 :
"F" → 0x0046 → 0000 0000 0100 0110

http://www.tamasoft.co.jp/en/general-info/unicode.html

public static String hexToBinary1(String hexNumber) {

    StringBuilder binary = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {

        char ch = str.charAt(i);
        int val;

        if(ch >= '0' && ch <= '9') {
            val = (int)ch - 0x30;
        else if(ch >= 'A' && ch <= 'F') {
            val = (int)ch - 0x41 + 0x0A;
        }

        for (int i = 0; i < 4; i++) {
            binary.append((val & 16) == 0 ? 0 : 1);
            val <<= 1;
        }
        binary.append(' ');
    }

    System.out.println("'" + s + "' to binary: " + binary);
    return binary.toString();
}

or

public static String hexToBinary1(String hexNumber) {
    return String.format("%16s", Integer.toBinaryString(Integer.parseInt(hexNumber, 16))).replace(" ", "0");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.