Home > other >  function to convers from hex to binary with all byte
function to convers from hex to binary with all byte

Time:12-09

I've tried a few solutions but all of them reduce the solution to only 6 bytes

for example if I send "3C" to this function it will show ----> 111100

I need it to be -----> 00111100

public static String hexToBinary(String hex) {
        int i = Integer.parseInt(hex, 16);
            
        String bin = Integer.toBinaryString(i);
        
        return bin;
        }

CodePudding user response:

Yes, I'm afraid Integer.toBinaryString is broken and printf doesn't help. You could do this:

public static String hexToBinary(String hex) {
    int i = Integer.parseInt(hex, 16);
    String bin = "00000000"   Integer.toBinaryString(i);
    return bin.substring(bin.length() - 8);
}

Though I wrote my own versions of these converters early on in the life of Java

  • Related