Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you mean "how large is an int" then <code>sizeof(int)</code> is the answer.</p> <p>If you mean "how small a type can I use to store values of this magnitude" then that's a bit more complex. If you already have the value in integer form, then presumably it fits in 4, 3, 2, or 1 bytes. For unsigned values, if it's 16777216 or over you need 4 bytes, 65536-16777216 requires 3 bytes, 256-65535 needs 2, and 0-255 fits in 1 byte. The formula for this comes from the fact that each byte can hold 8 bits, and each bit holds 2 digits, so 1 byte holds 2^8 values, ie. 256 (but starting at 0, so 0-255). 2 bytes therefore holds 2^16 values, ie. 65536, and so on.</p> <p>You can generalise that beyond the normal 4 bytes used for a typical int if you like. If you need to accommodate signed integers as well as unsigned, bear in mind that 1 bit is effectively used to store whether it is positive or negative, so the magnitude is 1 power of 2 less.</p> <p>You can calculate the number of bits you need iteratively from an integer by dividing it by two and discarding the remainder. Each division you can make and still have a non-zero value means you have one more bit of data in use - and every 8 bits you're using means 1 byte.</p> <p>A quick way of calculating this is to use the shift right function and compare the result against zero.</p> <pre><code>int value = 23534; // or whatever int bits = 0; while (value) { value &gt;&gt; 1; ++bits; } std::cout &lt;&lt; "Bits used = " &lt;&lt; bits &lt;&lt; std::endl; std::cout &lt;&lt; "Bytes used = " &lt;&lt; (bits / 8) + 1 &lt;&lt; std::endl; </code></pre>
 

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