Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

Integer.toBinaryString(data)

gives me a binary String representation of my array data.

However I would like a simple way to add leading zeros to it, since a byte array equal to zero gives me a "0" String.

I'd like a one-liner like this:

String dataStr = Integer.toBinaryString(data).equals("0") ? String.format(format, Integer.toBinaryString(data)) : Integer.toBinaryString(data);

Is String.format() the correct approach? If yes, what format String should I use? Thanks in advance!

Edit: The data array is of dynamic length, so should the number of leading zeros.

like image 402
tzippy Avatar asked Dec 10 '11 15:12

tzippy


People also ask

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you add a padding to a string in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How do I fill a string with 0?

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

How do you remove zeros at the beginning of a string in Java?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. The ^0+(?! $)"; To remove the leading zeros from a string pass this as first parameter and “” as second parameter.


1 Answers

For padding with, say, 5 leading zeroes, this will work:

String.format("%5s", Integer.toBinaryString(data)).replace(' ', '0');

You didn't specify the expected length of the string, in the sample code above I used 5, replace it with the proper value.

EDIT

I just noticed the comments. Sure you can build the pattern dynamically, but at some point you have to know the maximum expected size, depending on your problem, you'll know how to determine the value:

String formatPattern = "%" + maximumExpectedSize + "s";
like image 171
Óscar López Avatar answered Nov 14 '22 11:11

Óscar López