in printf()
I remember for unsigned there is %u
... but I can find no such %u
in specs for String.format()
so if I have a large unsigned
int then %d
will work correctly on it?
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.
%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.
The unsigned integer format is like the integer format except that the range of values does not include negative numbers. You should use the unsigned format only when non-negative integer data is expected.
If you want to treat an int as if it were unsigned you can to
int i = ...
String s = String.format("%d", i & 0xFFFFFFFFL);
This effectively turns the signed int into a long, but it will be from 0 .. 2^31-1
To do the reverse you can do
int i = (int) Long.parseLong(s);
String s2 = String.format("%d", i & 0xFFFFFFFFL);
And s2
will be the same as s
provided it is in range.
BTW: The simplest thing to do might be to use a long
in the first place. Unless you are creating a lot of these the extra memory is trivial and the code is simpler.
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