Pad a binary String equal to zero (“0”) with leading zeros in Java

后端 未结 5 1692
一整个雨季
一整个雨季 2021-01-02 09:22
Integer.toBinaryString(data)

gives me a binary String representation of my array data.

However I would like a simple way to add leading ze

5条回答
  •  借酒劲吻你
    2021-01-02 09:57

    You could override that function in your own class:

        public static String toBinaryString(int x){
    
            byte[] b = new byte[32]; // 32 bits per int
            int pos = 0;        
            do{
                x = x >> 1; // /2
                b[31-pos++] = (byte)(x % 2);
            }while(x > 0);
    
            return Arrays.toString(b);  
        }
    

提交回复
热议问题