views:

275

answers:

2

Hi.

I need to convert Java long datatype (64-bit) data into legacy c++ app unsigned int (32-bit) datatype.

No worries about the data loss as the data is Linux timestamp, which would take aeons to hit unsigned int limit.

Any idea what transformation to apply to these numbers?

Thanks in advance!

P.S. - data-types example:

Java - 1266336527340

C++ - 1266336583

They both produce same date, and about same time (+/- a minute).

+3  A: 

Java's Date.getTime returns the number of milliseconds from the epoch, whereas the C++ code expects the number of seconds from the epoch, so you need to divide by 1000 then truncate:

int timestampAsInt = (int)(timestampAsLong / 1000);

Java has only a signed integer not unsigned, but this should work.

Mark Byers
I tried this already - there is data loss and the resulting date is far in the future. Java for some reason fills out the whole 64-bit variable with a date.Example:Java - 1266336527340C++ - 1266336583C++ after casting from Java 3616142316 (back to the future :))
SyBer
Looking at your examples, it appears that you need to divide by 1000 first. I guess Java stores milliseconds from the epoch, whereas a 32-bit type would have seconds from the epoch.
Mark Byers
Updated my answer, and I've confirmed that if you use Date.getTime, you do indeed get the number of miiliseconds, not seconds which explains the factor 1000.
Mark Byers
Duh - should have understood it myself! :)
SyBer
+1  A: 
long javaTime = someDate.getTime();
int cTime = (int)((javaTime + 500) / 1000);

I prefer rounding over truncation, but you will have to decide which is right for your business rules.

Frank Krueger
Here you basically rounding up, right?
SyBer
No, I'm rounding using the normal rules. 1.5 rounds to 2.0. 1.4 rounds to 1.0. The beauty of integer arithmetic.
Frank Krueger
My bad - it rounded correctly indeed.
SyBer