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

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

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

0000000000000001
0000000000000010
0000000010000000
0000000100000000
17条回答
  •  猫巷女王i
    2020-11-22 08:30

    I would write my own util class with the method like below

    public class NumberFormatUtils {
    
    public static String longToBinString(long val) {
        char[] buffer = new char[64];
        Arrays.fill(buffer, '0');
        for (int i = 0; i < 64; ++i) {
            long mask = 1L << i;
            if ((val & mask) == mask) {
                buffer[63 - i] = '1';
            }
        }
        return new String(buffer);
    }
    
    public static void main(String... args) {
        long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
        System.out.println(value);
        System.out.println(Long.toBinaryString(value));
        System.out.println(NumberFormatUtils.longToBinString(value));
    }
    

    }

    Output:

    5
    101
    0000000000000000000000000000000000000000000000000000000000000101
    

    The same approach could be applied to any integral types. Pay attention to the type of mask

    long mask = 1L << i;

提交回复
热议问题