Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Several answers here state that if an <code>int</code> has a width of 16 bits, <code>0xFFFF</code> is negative. This is not true. <code>0xFFFF</code> is never negative.</p> <p>A hexadecimal literal is represented by the first of the following types that is large enough to contain it: <code>int</code>, <code>unsigned int</code>, <code>long</code>, and <code>unsigned long</code>.</p> <p>If <code>int</code> has a width of 16 bits, then <code>0xFFFF</code> is larger than the maximum value representable by an <code>int</code>. Thus, <code>0xFFFF</code> is of type <code>unsigned int</code>, which is guaranteed to be large enough to represent <code>0xFFFF</code>.</p> <p>When the usual arithmetic conversions are performed for evaluation of the <code>&amp;</code>, the <code>unsigned int</code> is converted to a <code>long</code>. The conversion of a 16-bit <code>unsigned int</code> to <code>long</code> is well-defined because every value representable by a 16-bit <code>unsigned int</code> is also representable by a 32-bit <code>long</code>. </p> <p>There's no sign extension needed because the initial type is not signed, and the result of using <code>0xFFFF</code> is the same as the result of using <code>0xFFFFL</code>.</p> <p>Alternatively, if <code>int</code> is wider than 16 bits, then <code>0xFFFF</code> is of type <code>int</code>. It is a signed, but positive, number. In this case both operands are signed, and <code>long</code> has the greater conversion rank, so the <code>int</code> is again promoted to <code>long</code> by the usual arithmetic conversions.</p> <hr> <p>As others have said, you should avoid performing bitwise operations on signed operands because the numeric result is dependent upon how signedness is represented.</p> <p>Aside from that, there's nothing particularly wrong with this code. I would argue that it's a style concern that <code>value</code> is not initialized when it is declared, but that's probably a nit-pick level comment and depends upon the contents of the <code>//some stuff</code> section that was omitted. </p> <p>It's probably also preferable to use a fixed-width integer type (like <code>uint32_t</code>) instead of <code>long</code> for greater portability, but really that too depends on the code you are writing and what your basic assumptions are.</p>
 

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