简体   繁体   中英

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

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 .

Try,

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

System.out.println(output);

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM