Sign extension from 16 to 32 bits in C

Sorin Cioban picture Sorin Cioban · Jun 2, 2011 · Viewed 40.7k times · Source

I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}

The instruction (instr) is 32 bits and inside it I have a 16bit number.

Answer

Nawaz picture Nawaz · Jun 2, 2011

Why is wrong with:

int16_t s = -890;
int32_t i = s;  //this does the job, doesn't it?