简体   繁体   中英

Hex to Binary String Java

I'm making Encryption now, and on the step 7 which i need to make the HEX String Array(which I have transferred from ASCII into a String Array) into Binary String.

public static void main(String[] args)  { 
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex           numbers that i save from last step

StringBuilder builder = new StringBuilder();
int l = 0;
for(String s : HS) {
    builder.append(s);
    if (s.length()<=1){
       stringHextoBinary[l] = HexToBinary(s.charAt(0));
         l++;
   System.out.print(HexToBinary(s.charAt(0)) + ",");

 }else{
    stringHextoBinary[l] = HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1));
        l++;
                   System.out.print(HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1))+",");
 }              

 public static String HexToBinary(char Hex) {
            int i = Integer.parseInt(Character.toString(Hex), 16);
            String Bin = Integer.toBinaryString(i);
            return Bin;
      }                 
 }

the if statement can be work with HEX when it has one digit or two digits. But my problem is here that it prints out HEX to Binary: 11100,111,111,10111,11101, its losing 0 in it. :(

so that when i encrypt word "apple" , and decrypt it with same code will come back with word "pppxl" :(

Hope I can get answer ASAP and thanks a lot!

Use this method of the Apache commons StringUtils class

public String leftPad(String str, int size, char padding);

after you've converted your number to 0s and 1s. It might look like

String paddedBin = StringUtils.leftPad(bin, 8, '0');

for example. Not sure how many digits you actually want to pad it to.

Instead of your method taking in chars, you can simply have it take in a string and convert it to binary using:

public static void main(String[] args)  { 
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex           numbers that i save from last step

// creates the string builder, count, and declaration
StringBuilder builder = new StringBuilder();
int l = 0;
string binaryDigits;

// iterates through string array and appends to string that's being built
// (for whatever reason)
for(String s : HS) {
    builder.append(s);
    binaryDigits = HexToBinary(s);
    stringHextoBinary[l++] = binaryDigits;
    System.out.print(binaryDigits);
}

// transforms hex string to binary string without losing 0's
public static String HexToBinary(String Hex) {
    string toReturn = new BigInteger(Hex, 16).toString(2);
    return String.format("%" + (Hex.length*4) + "s", toReturn).replace(' ', '0')
}

You don't need to combine code, as this is all the code that you need to convert a string to a binary string separated by spaces. It will iterate through and change every string to a binary string.

Try this method implementation:

public static String hexCharToBinary(char c) {
    final int v;
    if (c >= '0' && c <= '9') {
        v = c - '0';
    } else if (c >= 'A' && c <= 'F') {
        v = 10 + c - 'A';
    } else if (c >= 'a' && c <= 'f') {
        v = 10 + c - 'a';
    } else {
        throw new IllegalArgumentException();
    }
    return String.format("%4s", Integer.toBinaryString(v & 0xFF)).replace(' ', '0');
}    

Try this out:

stringHextoBinary[l] = new BigInteger(s,16).toString(2);

What this is doing is creating a new Integer with radix of 16 for you hex numbers and then converting that to a string of base 2 (binary). Haven't tested this out since I am not near a computer with a jvm installed but this is just an idea since you seem to need ideas in a hurry.

This should work too:

stringHextoBinary[l] = Integer.toBinaryString(Integer.parseInt(s, 16));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM