I am a student and I am writing a function in C to sign extend a given bit field. I'm working with 32 bits.
I looked this answer up on Google but didn't find what I was looking for.
I'm writing function that returns the twos complemnt representation of one or more consecutive bits pulled from a 32 int. The leftmost bit is the sign bit.
What do I return if I pull a single bit? How do you represent a single bit as a signed twos complment number?
It doesn't make much sense to talk a 1-bit two's complement number. If you only have 1 bit, it is either 0 or 1.
In general, if you have a two's complement number with N bits, the highest value expressible is 2^(N-1)-1
and the lowest value is -2^(N-1)
. If we want to be silly we can apply this to N=1 and we find that a 1-bit two's complement number can range from -1 to 0.
Edit: You wrote:
I'm writing function that returns the twos complemnt representation of one or more consecutive bits pulled from a 32 int. The leftmost bit is the sign bit.
I don't think this is well defined. Two's complement is an encoding that lets you represent a mathematical integer as a series of bits. Given an integer, it tells you what bits to store. I don't know what the two's complement representation of a series of bits would be. It's like you're asking me to give you the ASCII encoding of a series of arbitrary bytes, or you are asking me to translate the Gettysburg Address from French to English.