返回某些位范围内的有符号值

时间:2014-10-15 05:22:18

标签: c++ binary bits

作业:

  • 以位0-3
  • 返回4位的有符号值
  • 以位4-9
  • 返回6位的有符号值

分别

以下是一些例子:

signedBits0through3: input: 0x3fa, output: 0xfffffffa 
signedBits0through3: input: 0x3f7, output: 0x07 
signedBits4through9: input: 0x38f, output: 0xfffffff8 
signedBits4through9: input: 0x18f, output: 0x18 
// return the signed value in bits 0 through 4

int signedBits0through3(int v)
{
    if (((v & 15) & (1<<3))== 0) {
        return (v & 15);
    }
    else
        return ~(v & 15);
}

// return the signed value in bits 4 through 9

int signedBits4through9(int v)
{
    if (((v & 1008)&(1<<9))==(1<<9)) {
        return ~((v & 1008)>>4);
    }
    else    
        return ((v & 1008)>>4);
}

任何帮助!!

1 个答案:

答案 0 :(得分:-1)

它比你想象的要简单得多。只是一点点掩蔽,符号延伸和向后移动。

// return the signed value in bits 0 through 3
int signedBits0through3(int v)
{
    return ((v  & 0xf) << 28) >> 28;
}

// return the signed value in bits 4 through 9
int signedBits4through9(int v)
{
    return ((v  & 0x3f0) << 22) >> 26;
}