I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:
//the variable name of the binary string is: "binary"
int digitNumber = 1;
int sum = 0;
int test = binary.length()%4;
if(test!=0) {
binary = padLeft(binary, test);
}
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
public static String padLeft(String s, int n) {
return String.format("%0$"+n+"s", s);
}//i added this for padding
the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:
http://www.wikihow.com/Convert-Binary-to-Hexadecimal
PS: I need to implement it(not using any built-in function)
If you don't have to implement that conversion yourself, you can use existing code :
int decimal = Integer.parseInt(binaryStr,2);
String hexStr = Integer.toString(decimal,16);
If you must implement it yourself, there are several problems in your code :
sum
must be reset to 0 after each hex digit you output.System.out.print(digitNumber);
- here you should print sum
, not digitNumber
.Here's how the mostly fixed code looks :
int digitNumber = 1;
int sum = 0;
String binary = "011110101010";
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
Output :
7AA
This will work only if the number of binary digits is divisable by 4, so you must add left 0
padding as a preliminray step.