toBinaryString in Java removes leading 0...help?

Avalon

Diamond Member
Jul 16, 2001
7,569
172
106
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?
 
Sep 29, 2004
18,656
67
91
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.
 

Avalon

Diamond Member
Jul 16, 2001
7,569
172
106
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.
 

statik213

Golden Member
Oct 31, 2004
1,654
0
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);