Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
void Generic::IntToS16 (S16 & Out_, int & In_){
    unsigned char * bytes_in = reinterpret_cast<unsigned char*> (&In_);
    unsigned char * bytes_out = reinterpret_cast<unsigned char*> (&Out_); 
    bytes_out[1] = bytes_in[1];
    bytes_out[0] = bytes_in[0];

    bytes_out[1] |= bytes_in[sizeof(int)-1] & 1<<7;
}

---OR---

short Generic::IntToS16 (int In_){
    short ret = static_cast<short>(In_);
    return ret;
}
share|improve this question
I'm surprised this question was asked. Isn't it obvious? – asveikau Oct 20 '12 at 5:25

2 Answers

up vote 4 down vote accepted

The first method is not a cast, it's an architecture-dependent operation that will produce invalid results on litte-endian architectures. In other words, it is not portable.

The second cast, however, is portable, because it lets the compiler generate the correct sequence of operations.

share|improve this answer

OR

short Generic::IntToS16 (int In_){
    return In_;
}

Note: short is not necessarily 16 bits long (it is at least 16 bits but could be longer).

You can of course use: int16_t

Also note casting from a large integer type to a smaller may result in implementation defined values:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.