I am trying to write a program that either zero extends or sign extends a 16 bit input to a 32 bit output, what exactly is meant by sign extending a number? I believe zero extending would be adding 16 0s in the 16 Most Significant bits, Is sign extending just keeping the most significant bit as the sign?

Sign-extending means the value of the most significant bit of the 16-bit integer (the sign bit, for signed 16-bit integers) is used to fill the 16 higher bits.

0abcdefghijklmno => 00000000000000000abcdefghijklmno
1abcdefghijklmno => 11111111111111111abcdefghijklmno

This means that if your 16 bits represent a signed integer, your 32-bit value will represent the same integer.

When you write

int16_t x = -5;
int32_t y = x;

the value gets cast up to a 32-bit signed integer using the sign extension described above. If zero extension were used instead, y would be assigned the value 65531, instead of -5.

commented: Thank you +1

Hi any ideas on how to do this using C?

C decides whether to sign extend or zero-extend when you cast an integer type based on whether it's signed or unsigned.

well the thing is im writing a code to take a hexadecimal input which is a 32 bit instruction. The last 16bits of this instruction is a constant which i have to add to another value. But apparently i can't add it because its 16bits long and im adding to 32 bit register value. Just wondering if there's a way to make this 16bits long into 32 bits long ? Thanks

#define BITMASK 0xffff0000
return (x >> 15 == 0) ? x : (x | BITMASK)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.