-1

I have this Code:

    String hexCode = "A1E1F1";
    int länge = hexCode.length ();
    int i;

    for (i = 0; i <= länge - 1 ; i ++) {

    char pos = hexCode.charAt(i);

        String binCode = Integer.toBinaryString(pos);

    System.out.print ( binCode);    

When I run it I get this result:

100000111000110001011100011000110110001 

Which I don't believe is correct. Shouldn't it be:

101000011110000111110001

Are these results actually the same? Why does java give me the first result?

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
  • I suggest you read the documentation for toBinaryString(). The simple solution is to parse the hex as hexidecimal and to write it as binary. Are you required to example each character? – Peter Lawrey Nov 25 '14 at 17:14
  • Note that `toBinaryString` removes leading zeros, so the actual length of the result string will vary. Also note that `print` will be called 6 times, and the outputs will all be smashed together. This means that it's impossible to look at the output and tell where one binary string starts and the other ends. That's usually not what you want (but who knows, maybe it is). – ajb Nov 25 '14 at 17:14
  • I see that you were trying to output hex digits. It still won't work, because `toBinaryString` on 1 will return `"1"`, not `"0001"`. – ajb Nov 25 '14 at 17:16
  • ProTip: If you're wondering whether a relatively straightforward method in a widely-used JDK class that has been around [since JDK 1.0.2](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int)) is incorrect -- the answer is almost always "no." – yshavit Nov 25 '14 at 17:19
  • See http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java for some ideas of how to format the number in binary and include leading zeros. – ajb Nov 25 '14 at 17:20

2 Answers2

6

You aren't parsing your input string as a HEX representation. You're taking each character, getting its char value and converting that to binary representation.

What you want is to parse the input text as a base 16 integer

String hexCode = "A1E1F1";
int val = Integer.parseInt(hexCode, 16);
System.out.println(Integer.toBinaryString(val));
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
5

Yes. Integer.toBinaryString is correct. Your answer is the binary of pos without any newlines.

1000001
110001
1000101
110001
1000110
110001

The output you expected requires you to decode the digit value. Like

String binCode = Integer.toBinaryString(Character.digit(pos, 16));

Then the output is

101011110111111
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Which still isn't what he wants--I think he wants a four-character string for every hex digit. Thus `toBinaryString` won't work since it strips leading zeroes. – ajb Nov 25 '14 at 17:16