Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating a String containing a binary value to Hex

I am trying to translate a String that contains a binary value (e.g. 000010001010011) to it's Hex value.(453)

I've been trying several options, but mostly I get a converted value of each individual character. (0=30 1=31)

I have a function that translates my input to binary code through a non-mathematical way, but through a series of "if, else if" statements. (the values are not calculated, because they are not standard.) The binary code is contained in a variable String "binOutput"

I currently have something like this:

        String bin = Integer.toHexString(Integer.parseInt(binOutput));

But this does not work at all.

like image 756
N-Aero Avatar asked Apr 22 '11 21:04

N-Aero


2 Answers

Try using Integer.parseInt(binOutput, 2) instead of Integer.parseInt(binOutput)

like image 168
Ted Hopp Avatar answered Oct 22 '22 15:10

Ted Hopp


Ted Hopp beat me to it, but here goes anyway:

jcomeau@intrepid:/tmp$ cat test.java; java test 000010001010011
public class test {
 public static void main(String[] args) {
  for (int i = 0; i < args.length; i++) {
   System.out.println("The value of " + args[i] + " is " +
    Integer.toHexString(Integer.parseInt(args[i], 2)));
  }
 }
}
The value of 000010001010011 is 453
like image 28
jcomeau_ictx Avatar answered Oct 22 '22 15:10

jcomeau_ictx