问题
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?
回答1:
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.
回答2:
As I understand it, you want to pluck N arbitrary bits (N >= 1 & <=32) from a bit stream in a 32-bit variable and represent them as a 2's complement number (presumably returning that number as a signed int 32).
What this says is that you take the selected bits, place them in the low-order (ie, right) end of a work variable, and then "extend" the left-most selected bit by propagating (copying) it leftward through the remaining (previously undefined) bits in the work variable. This can be done as a single consistent algorithm, with no need to special-case any particular value of N.
For two bits it will produce the possible values 1, 0, -1, and -2 (for bit patterns 01, 00, 11, and 10 respectively). For one bit it will produce the possible values 0 and -1 (for bit patterns 0 and 1 respectively).
来源:https://stackoverflow.com/questions/12240925/sign-extend-1-bit-2s-complement-number