i was reading and couldn't find quite the snippet. I am looking for a function that takes in a string and left pads zeros (0) until the entire string is 8 digits long. All the other snippets i find only lets the integer control how much to pad and not how much to pad until the entire string is x digits long. in java.
Example
BC238 => 000BC289
4 => 00000004
etc thanks.
If you're starting with a string that you know is <= 8 characters long, you can do something like this:
s = "00000000".substring(0, 8 - s.length()) + s;
Actually, this works as well:
s = "00000000".substring(s.length()) + s;
If you're not sure that s
is at most 8 characters long, you need to test it before using either of the above (or use Math.min(8, s.length())
or be prepared to catch an IndexOutOfBoundsException
).
If you're starting with an integer and want to convert it to hex with padding, you can do this:
String s = String.format("%08x", Integer.valueOf(val));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With