Double to long conversion

I work in the field(though only have been for two years mind), and I feel silly asking a begginner type question like this, but short of reworking the system around the problem, I thought I'd ask about this conversion problem I've been having.

I was testing it a bit, and at the moment essentially the code looks like this: (not exact, of course)
1
2
3
4
5
double x; //set much earlier, contains more info.
...
long startDate = getstartdate();
double tempStartDate = x - (double)startDate;
long newStartDate = (long)tempStartDate;

I realize I could have skipped the temp variable, that was more for your sake and what I'm about to say next.
the values of each variable after this runs are as follows:

startDate = -1543536000
x = 2751408000.00000000
tempStartDate = 4294944000.00000000
newStartDate = -2147483648

It makes no sense... Why after I convert from double to long does it go from positive 4294944000 to negative 2147483648!?!?

The function works fine with normal dates 1970 and later, but as soon as you put in a date less than 1970 it starts flipping out with the negative numbers.

It would be bad programming to PREVENT them from inputting numbers prior to 1970, I'm pretty sure they don't have any DATA from back then, so it'll only pull up a blank screen, but I still can't have the dang thing crash.

EDIT: nvm, I should have just played with it a bit more before panicking... I still don't know why it won't convert from double to long, but it converts from double to unsigned int juuuust fine, and my boss had mentioned something about wanting to make everything unsigned ints anyway.
Last edited on
I don't think a long integer can hold a value as large as 4294944000. Even an unsigned long integer might barely not be in range.
too large? huh, it's 4 bytes whereas a double is 8 bytes, didn't do the math on it, but considering i've been doing calculations that take that number and times it by 100 that have been working fine, I'm not quite sure that's the problem... And the thing is, it started not working when I started testing with SMALLER numbers...
If long is 32 bits, the value 4294944000 cannot be held in a signed long. It can, however, be stored in an unsigned long.

2,147,483,647 is the maximum value that can be held in a signed 32 bit integer variable.

4,294,967,295 is the maximum value that can be held in an unsigned 32 bit integer variable.

If there is a 64 bit integer type available to you, you should consider using it here.
Last edited on
Good to know. Makes me wonder how some of this stuff was working before I got to it. Thanks for your insight in any case.
Last edited on
Random suggestion: try unsigned long long?
Topic archived. No new replies allowed.