Long multiplication and result overflow

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pjerald
    New Member
    • Oct 2007
    • 77

    Long multiplication and result overflow

    What is important to Understand about these two functions when multiplying integers and converting it to Long value.

    ONE WAY.
    long convertDaysToMi lliseconds(int days) { return 1000*3600*24*da ys; }

    ANOTHER WAY
    long convertDaysToMi lliseconds(int days) { return 1000L*3600*24*d ays; }

    OR
    static final long MILLISECONDS_PE R_DAY = 24L*3600*1000;
    long convertDaysToMi lliseconds(int days) { return days * MILLISECONDS_PE R_DAY; }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by pjerald
    What is important to Understand about these two functions when multiplying integers and converting it to Long value.

    ONE WAY.
    long convertDaysToMi lliseconds(int days) { return 1000*3600*24*da ys; }

    ANOTHER WAY
    long convertDaysToMi lliseconds(int days) { return 1000L*3600*24*d ays; }

    OR
    static final long MILLISECONDS_PE R_DAY = 24L*3600*1000;
    long convertDaysToMi lliseconds(int days) { return days * MILLISECONDS_PE R_DAY; }
    Erm, those are *three* functions, not two. No need to worry though, I'm off by one
    almost all the time. (the first method can cause int overflow).

    kind regards,

    Jos ;-)

    Comment

    Working...