sign extend 1-bit 2's complement number?

后端 未结 2 1713
盖世英雄少女心
盖世英雄少女心 2021-01-23 10:09

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 w

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-23 10:39

    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).

提交回复
热议问题