toBinaryString in Java removes leading 0...help?

Discussion in 'Programming' started by Avalon, Oct 16, 2007.

  1. Avalon

    Avalon Diamond Member

    Joined:
    Jul 16, 2001
    Messages:
    7,384
    Likes Received:
    1
    Does anyone know of a way to keep the leading 0 when a decimal is converted into a binary?
    Say I'm converting 121 into binary, which would be 01111001. Instead, it hacks off the 0 and gives me 1111001, which is also correct, but I require that leading 0 so my program doesn't lose its place. Is there any way around that, or should I be using a different method?
     
  2. IHateMyJob2004

    Joined:
    Sep 29, 2004
    Messages:
    17,699
    Likes Received:
    1
    EWither Java 1.5 or 6 has formatted strings.

    Much like the printf commands in C.

    I've never used the new output functionality though.

    I hope you are referring to displaying the value.





    If you are talking about how it is stored in memmory, the leading 0 is not needed so give up.
     
  3. Avalon

    Avalon Diamond Member

    Joined:
    Jul 16, 2001
    Messages:
    7,384
    Likes Received:
    1
    Well, the reason I need it is because i have to XOR two values in my 8 bit binary string. Say my program says I XOR bit 1 and bit 8 of every 8 bit binary string. In my above case, I'd be XOR'ing 0 and 1, to get 1. However, since the leading 0 is being discarded, my program would XOR 1 and nothing, and then error out.

    I think I figured it out though, by just inputting the binary value into a character array and adding leading 0's for however many characters I was short of 8 bits.
     
  4. statik213

    statik213 Golden Member

    Joined:
    Oct 31, 2004
    Messages:
    1,654
    Likes Received:
    0
    You should not be doing xors using string operations... Use the btiwise operators for your bit level mainpulation.

    All you need to do is something like this:

    String num1 = "42";
    String num2 = "137";

    int result = Integer.parseInt(num1) ^ Integer.parseInt(num2);

    String binary = Integer.toBinaryString(result);
    String formatted = String.format("%8s", binary);
     
Loading...