Translating a String containing a binary value to Hex

15,478

Solution 1

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

Solution 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
Share:
15,478
N-Aero
Author by

N-Aero

Updated on June 15, 2022

Comments

  • N-Aero
    N-Aero almost 2 years

    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.

  • RRTW
    RRTW over 10 years
    Good answer, thanks, and what if I want "00000001" to be output as "01", not just only "1" ?
  • Ted Hopp
    Ted Hopp over 10 years
    @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?
  • RRTW
    RRTW over 10 years
    Yes I want leading zero always :-), as your hint, I'll try done this with String.format, thanks~
  • Ted Hopp
    Ted Hopp over 10 years
    @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.)