Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does %d in String.format() work for unsigned integers also?

Tags:

java

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?

like image 607
ycomp Avatar asked Aug 13 '13 07:08

ycomp


People also ask

What is string format () and how can we use 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.

What is the function of %D in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.

What is unsigned integer format?

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.


1 Answers

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.

like image 75
Peter Lawrey Avatar answered Oct 21 '22 04:10

Peter Lawrey