7

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.

2
  • Wow, yo guys are fast! And it works! Thanks! But I have 1 issue remaining... when the numbers are larger it does not seem to work.(e.g. "1011000010001010011101010110110011001000010011111" should become 16114EAD9909F) Commented Apr 23, 2011 at 6:33
  • The problem is that the value does not fit in an int. Try String bin = Long.toHexString(Long.parseLong(binOutput, 2)); If it gets too big for even a long (64 bits), then you're going to have to break binOutput into smaller strings and do each piece separately. Commented Apr 24, 2011 at 1:16

2 Answers 2

16

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

Sign up to request clarification or add additional context in comments.

4 Comments

Good answer, thanks, and what if I want "00000001" to be output as "01", not just only "1" ?
@RRTW - Are you asking about the inverse problem: converting an integer value to a string? This can be done in a variety of ways: Integer.toString(), String.format, and a few others. Your requirement is not clear. Do you always want a leading zero? Do you always want at least two digits? Something else?
Yes I want leading zero always :-), as your hint, I'll try done this with String.format, thanks~
@RRTW - If you want to format a non-negative integer value as a binary string with a leading zero, you can simply use "0" + Integer.toString(value, 2). (That will generate "00" for zero, so you might want a special check for that case.)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.