-1

bit computer in java and i have run into a weird problem. i have a binary number stored as an integer and i needed to convert it to a string but when i do the Integer.toString() returns 9 when i gave it 00000011 but it should have returned 3 right? here's the function i was making

static int binToInt(int bin)
{
    String binary = Integer.toString(bin);
    return Integer.parseInt(binary, 2);
}

Can someone explain? i have been trying for over an hour to find a solution. either i find a page with something else or a tutorial of how to use Integer.toString()

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    In Java, the literal 00000011 is an octal number, not a binary number, and it is (decimal) 9. In recent Java versions, you can use the binary literal 0b000011. – Mark Rotteveel Jun 02 '20 at 17:50
  • Include the exact details: what *specifically* are you passing to `binToInt`? – Dave Newton Jun 02 '20 at 17:50
  • There is a method Integer.ToBinaryString() or Integer.toString(int i, int radix), maybe try to add a radix of 2 to let it know it's a binary number – EdwynZN Jun 02 '20 at 18:06
  • @EdwynZN i have already done that still returns 9. – Patrick Frederiksen Jun 02 '20 at 18:12
  • it's your binary number in the format 0b0011? – EdwynZN Jun 02 '20 at 18:15
  • @EdwynZN no and i know it would solve the problem but i don't know how to add 0b to the front because i did just start with java 5 days ago or so. – Patrick Frederiksen Jun 02 '20 at 18:18
  • You can't add anything to the "front" of an integer (well, I mean, you do math on it). You can add things to the front of *strings*. It is not clear how you are calling this method--but it expects an `int`, and `011` is a different int value than `11`. – Dave Newton Jun 02 '20 at 18:32
  • running your code in a simple online java compiler gave me no error, int x = binToInt(11); System.out.println(x); gave me an output of 3, but it does give me 9 if I use toString(bin, 2) with bin = 000011, the compiler saw that you're giving an int with 0 to the left and is thinking it's an octal number (when its not, its just a simple int that you wrote to look like a binary), try sending bin as 11 (3) with no left zeros. 0000011 in octal is 9 and that is what is sending back as a String – EdwynZN Jun 02 '20 at 18:55

1 Answers1

-2

Please include a full program, or at least an example where you call your method the next time.

But if you do int val=00000011, then val will be 9, because java treats numbers starting with 0 as octal.

MTilsted
  • 5,425
  • 9
  • 44
  • 76