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

后端 未结 5 1669
一整个雨季
一整个雨季 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:39

    This is what you asked for—padding is added only when the value is zero.

    String s = (data == 0) ? String.format("%0" + len + 'd', 0) : Integer.toBinaryString(data);
    

    If what you really want is for all binary values to be padded so that they are the same length, I use something like this:

    String pad = String.format("%0" + len + 'd', 0);
    String s = Integer.toBinaryString(data);
    s = pad.substring(s.length()) + s;
    

    Using String.format() directly would be the best, but it only supports decimal, hexadecimal, and octal, not binary.

提交回复
热议问题