0

I know about Integer.toBinaryString(int i) , but what I am trying to decide how to do is append a certain number of bits (0's) to the end of it as needed.

Example: I have the integer 3 which is represented by 11 in binary, but I want it to be 7 digits (bits) long in total so it will get the length of the binary value (in this case 2 bits) and then add 5 0's to the start so you will finish with 0000011 for a total of 7 bits.

HybrisHelp
  • 5,518
  • 2
  • 27
  • 65
KoolAid
  • 299
  • 1
  • 4
  • 13
  • 1
    If you're treating it as a string, use a loop to concatenate `"0"`s to the front of it. If you're treating this an `int`, there's no need to do any kind of manipulation; the value will remain 0x03 regardless. – musical_coder Nov 27 '13 at 06:08
  • 2
    You can look at this - [How to get 0-padded binary representation of an integer in java?](http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java), looks similer – Subhrajyoti Majumder Nov 27 '13 at 06:09
  • http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – craiglm Nov 27 '13 at 06:10

2 Answers2

2

Try,

String output= String.format("%"+numberOfZerosToPut+"s",
                  Integer.toBinaryString(3)).replace(' ', '0');

System.out.println(output);
Masudul
  • 21,823
  • 5
  • 43
  • 58
  • Works like a charm, Thank you!! Also, for those reading this with similar problems other than the example I used, you can change the code to be String output= String.format("%"+numberOfZerosToPut+"s", Integer.toBinaryString(3)).replace(' ', '0'); And it will simply put the number of 0s necessary at the front of the binary value. – KoolAid Nov 27 '13 at 06:20
  • But this will work for a limited values that can be formed using 8 bits only. – Nishant Lakhara Nov 27 '13 at 06:22
  • @nishu, Yes, it will be work for 7 bits, As OP mentioned 7 bits to his question. – Masudul Nov 27 '13 at 06:24
  • @nishu I tested it with something that only required 4 bits (integer value of 9) but I told it I needed 9 bits total and it worked perfectly. – KoolAid Nov 27 '13 at 06:33
  • Ok If no of bits are known. – Nishant Lakhara Nov 27 '13 at 09:37
0

Create a method like this :

public static String appendZeroes(String bits) {
        int rem = bits.length()%8;
        if(rem == 0)
            return bits;
        else
        {
            int appendingZeroes = 8-rem;
            String s = "";
            for(int i=0;i<appendingZeroes;i++)
                s+="0";
            s=s+bits;
            return s;
        }
    }
Nishant Lakhara
  • 2,295
  • 4
  • 23
  • 46