换一位(此位应为'1')

时间:2011-12-10 18:09:58

标签: c bit shift

代码 - 评论:

void main()
{
    unsigned int BHR;

    BHR = (BHR << 1);  /*shifting left by one */
    BHR = (BHR | 0x1);  /* ?????, how can i do this? shifted bit = 1 (LSB of BHR) */         
    BHR = (BHR & 0xFFFFFFFE);  /* shifted bit = 0 (LSB of BHR)
}

2 个答案:

答案 0 :(得分:4)

您的示例中只有一个位移动:

BHR = (BHR << 1);

接下来的两个是OR和AND,所以让我们举一个例子(假设BHR被初始化为某个值,这在你的代码中不会发生):

unsigned int BHR = 5;     // in binary BHR = 00000000000000000000000000000101
BHR = (BHR << 1);         //           BHR = 00000000000000000000000000001010

BHR = (BHR | 0x1);        //           BHR = 00000000000000000000000000001010
                          // |         0x1 = 00000000000000000000000000000001
                          //           --------------------------------------
                          //     new BHR   = 00000000000000000000000000001011

BHR = (BHR & 0xFFFFFFFE); //           BHR = 00000000000000000000000000001011
                          //  & 0xFFFFFFFE = 11111111111111111111111111111110
                          //           --------------------------------------
                          //     new BHR   = 00000000000000000000000000001010

答案 1 :(得分:0)

我认为您在设置位时会混淆移位操作。

BHR = (BHR << 1);

这行代码会将unsigned int BHR一个位置的所有位向左移位,并用零填充最小指示位。如果当时BHR恰好为零,那么这不会影响该值。 OR操作BHR = (BHR | 0x01)实际上将最低有效位设置为1.