Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simplest way is to use 64-bit integer type, but I assume you cannot do this. Since you want your answer in 32-bit integer, the high-order value of microseconds cannot be greater than 999, or it would not fit in 32-bit after division by 1000. So the bigger number of microseconds you're operating with is <code>999 * 2^32 + (2^32 - 1) = 4294967295999</code>. It gives you 13 decimal digits and you can use <code>double</code> to handle precise division.</p> <p>If you are forced for some reason to use only 32-bit integers, the answer of Michał Górny gives you an <em>approximate</em> solution. E.g. for <code>whole_number = 1234567890123</code> it will give a result of <code>1234567805</code>. Because dividing of max 32-bit int on 1000 have a reminder.</p> <p>The only way to have an exact answer with 32-bit integer is by using long arithmetic. It requires long digits to be stored in a type which can be extended to store a reminder. You have to split your two 32-bit integers in four 16-bit digits. After that you can divide it as on paper and you have enough bits to store a reminder. See the code of <code>micro2milli</code>:</p> <pre><code>#include &lt;iostream&gt; typedef unsigned __int32 uint32; typedef unsigned __int64 uint64; const uint32 MAX_INT = 0xFFFFFFFF; uint32 micro2milli(uint32 hi, uint32 lo) { if (hi &gt;= 1000) { throw std::runtime_error("Cannot store milliseconds in uint32!"); } uint32 r = (lo &gt;&gt; 16) + (hi &lt;&lt; 16); uint32 ans = r / 1000; r = ((r % 1000) &lt;&lt; 16) + (lo &amp; 0xFFFF); ans = (ans &lt;&lt; 16) + r / 1000; return ans; } uint32 micro2milli_simple(uint32 hi, uint32 lo) { lo /= 1000; return lo + (hi % 1000) * 4294967L; } void main() { uint64 micro = 1234567890123; uint32 micro_high = micro &gt;&gt; 32; uint32 micro_low = micro &amp; MAX_INT; // 1234567805 std::cout &lt;&lt; micro2milli_simple(micro_high, micro_low) &lt;&lt; std::endl; // 1234567890 std::cout &lt;&lt; micro2milli(micro_high, micro_low) &lt;&lt; std::endl; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload