How to get 0-padded binary representation of an integer in java?

前端 未结 17 1912
我在风中等你
我在风中等你 2020-11-22 08:23

for example, for 1, 2, 128, 256 the output can be (16 digits):

0000000000000001
0000000000000010
0000000010000000
0000000100000000
相关标签:
17条回答
  • 2020-11-22 08:43

    A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":

    private String toBinaryString32(int i) {
        String binaryWithOutLeading0 = Integer.toBinaryString(i);
        return "00000000000000000000000000000000"
                .substring(binaryWithOutLeading0.length())
                + binaryWithOutLeading0;
    }
    
    0 讨论(0)
  • 2020-11-22 08:45

    I think this is a suboptimal solution, but you could do

    String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
    
    0 讨论(0)
  • 2020-11-22 08:46

    This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.

    static String toBitString( int x, int bits ){
        String bitString = Integer.toBinaryString(x);
        int size = bitString.length();
        StringBuilder sb = new StringBuilder( bits );
        if( bits > size ){
            for( int i=0; i<bits-size; i++ )
                sb.append('0');
            sb.append( bitString );
        }else
            sb = sb.append( bitString.substring(size-bits, size) );
    
        return sb.toString();
    }
    
    0 讨论(0)
  • 2020-11-22 08:47
    for(int i=0;i<n;i++)
    {
      for(int j=str[i].length();j<4;j++)
      str[i]="0".concat(str[i]);
    }
    

    str[i].length() is length of number say 2 in binary is 01 which is length 2 change 4 to desired max length of number. This can be optimized to O(n). by using continue.

    0 讨论(0)
  • 2020-11-22 08:47

    // Below will handle proper sizes

    public static String binaryString(int i) {
        return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
    }
    
    public static String binaryString(long i) {
        return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
    }
    
    0 讨论(0)
  • 2020-11-22 08:47
    import java.util.Scanner;
    public class Q3{
      public static void main(String[] args) {
        Scanner scn=new Scanner(System.in);
        System.out.println("Enter a number:");
        int num=scn.nextInt();
        int numB=Integer.parseInt(Integer.toBinaryString(num));
        String strB=String.format("%08d",numB);//makes a 8 character code
        if(num>=1 && num<=255){
         System.out.println(strB);
        }else{
            System.out.println("Number should be in range between 1 and 255");
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题