简体   繁体   中英

casting long to int

I have one variable which gets current time and stored in long. But I have to convert it to int as it is the requirement. So what i am doing is converting the val with (int) and storing inside the int.

Val = 1355399741522 (long)
Int Val = -1809346991 (after casting to int)

After Casting from int to long -> Val = -1809346991 //TESTED

Now my question is if I want to convert this int again back to long than definitely it will not going to work for me. That i already tested. But I want alternate solution for this.

NOTE - I don't want to store long. As its the requirement. And I am using below function to convert the long to time

public static String convertToTime(final long date) {
        String time = null;
        final SimpleDateFormat bartDateFormat1 = new SimpleDateFormat("HH");
        final SimpleDateFormat bartDateFormat2 = new SimpleDateFormat("mm");
        final Date fomDat = new Date(date);
        final int hour = Integer.parseInt(bartDateFormat1.format(fomDat));
        final int min = Integer.parseInt(bartDateFormat2.format(fomDat));
        time = pad(hour) + ":" + pad(min);
        return time;
    }

If anyone has any idea please kindly guide me or provide any alternative.

If you have a long that contains a value greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE , and you cast it to an int and then back to a long , you won't get the original value back again.

If you have a "requirement" to do that, then your requirement is not implementable. What you are trying to do is a mathematical impossibility.

(You should also consider the possibility that you have misunderstood the requirement ...)

When time is stored as an int it's usually in seconds because milli-seconds will not fit. If you do this

long timeInMs = 1355399741522L;
int timeInSec = (int) (timeInMs / 1000); // now 1355399741
long timeInMs2 = timeInSec * 1000L; // now 1355399741000L

You can convert the long to String and create an Integer(String) object. but since the Long.MAX_VALUE(2^63-1) is much more than the Integer.MAX_VALUE(2^31 - 1), you have to make a compromise on the length of the long variable if that exceeds the maximum length of the integer type.

public static String convertToTime(final long date) {
        String time = null;
        final SimpleDateFormat bartDateFormat1 = new SimpleDateFormat("H:m");
        time = bartDateFormat1.format( date );
        return time;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM