How to convert an integer to a binary representation that also appends a certain number of bits as needed

StackOverflow https://stackoverflow.com/questions/20235088

  •  05-08-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

Try,

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

System.out.println(output);

OTHER TIPS

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;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top