int castToShort(int v) { int m = v & 0xFFFF; if (m >= 32768){ // handle two's compliment m = -32768 + (m - 32768); } return m; }