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

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

    would this satisfy your needs?

    String dataStr = data == 0 ? "00" +   Integer.toBinaryString(data)  : Integer.toBinaryString(data);
    

    edit: noticed the comment about dynamic length: probably some of the other answers are more suited:)

提交回复
热议问题