Reputation: 15163
I'm trying to convert a double into an unsigned int in Java.
With unsigned int I mean the range from 0 to 4294967295.
I use int
as carrier - and it can be converted to a String with Integer.toUnsignedString
.
I don't care what result I get if
NaN
.Inf
or -Inf
< 0
or > 4294967295
.As long as I get any result.
A simple cast does not work:
(int) 4294967295d == 2147483647
(int) 2147483648d == 2147483647
So the problematic range is 2147483648d
- 4294967295d
.
Is there a fast way to cover that range correctly?
tl;dr: In C I would use (unsigned int) dblValue
- what would I use in Java for that?
Upvotes: 0
Views: 992
Reputation: 103018
4294967295f
That's not a thing. That float does not exist. It gets rounded. Don't use floats, there's almost no point to them. It works as a double.
Is there a fast way to cover that range correctly?
Once you realize that your question makes no sense and move to doubles instead, yeah. Cast to long, cast to int:
double d = 4294967295.0;
int i = (int) (long) d;
System.out.println(i);
System.out.println(Integer.toUnsignedString(i));
> -1
> 4294967295
Upvotes: 6