title: Casting negative numbers
body: <p>I am trying to interpret hex bytes and consolidate them into useful information.</p>
  
  <pre><code>void processData(){
    signed char data;
    unsigned long a;//holds four bytes
    unsigned long b;
    unsigned int c;//holds two bytes
    unsigned char d;//holds one byte
  
    a=readA();//readA,readB,readC,readD return one unsigned byte;
    b=readB();
    c=readC();
    d=readD();
  
    data=(signed char) ((0xffffffff-((a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)))/1000);
  
  }
  </code></pre>
  
  <p>The scenario is that the whole package received contains a four-byte information, for example a value of 0xAABBCCDD. readA() will return the highest byte in the package i.e. 0xAA. readD() will return 0xDD. So I need to shift them before using "|" to put them together: <code>(a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)</code></p>
  
  <p>So my question is, for right hand side of this sentence</p>
  
  <p><code>data=(signed char) ((0xffffffff-((a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)))/1000);</code></p>
  
  <p>why does it not return a char while I cast the result to a signed char? When I print it out everything is wrong. However, if I set <code>data</code> as signed long, everything is correct. I guess it's because signed char was not big enough to hold all information and caused overflows.</p>
  
  <p>Correct me if I am wrong, variables in <code>((a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)))</code> will all be implicitly cast to unsigned long and so is the result of this expression. <code>((a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)))/1000</code> will also return a unsigned long number. However the result will be significantly smaller since it's divided by 1000.   </p>
  
  <p>The four-byte information ranges from 0xFFFF5037 to 0xFFFFFFFF, which is also the range of the result of this expression <code>((a&lt;&lt;24)|(b&lt;&lt;16)|(c&lt;&lt;8)|(d)))</code>.</p>
  
  <p>So the right hand side of the expression should be between 0 to 45 after the division is done. But when I print the result it's all jumping around.</p>