用C语言进行按位运算

函数set_bit(uint64_tx,int pos,bool value)的主体,返回输入x的修改后的值,其中pos位置的位替换为值。

请记住,在C语言中(这是在stdbool.h中定义的),true是整数1,而false是整数0。

代码

uint8_t a=0b00000000;
uint8_t b=0b00001000;
uint8_t c=0b11111101;
uint8_t d=0b11011011;

// l'opération  ~( a ) renvoi 0b11111111
// l'opération (c & a) renvoi 0b00000000
// l'opération (c & b) renvoi 0b00001000
// l'opération (a | b) renvoi 0b00001000
// l'opération (d & c) renvoi 0b11011001  

#include <stdint.h>
#include <stdbool.h>

/*
* @pre 0<= pos < 64
*/

uint64_t set_bit(uint64_t x,bool value)
{
    // à compléter
}
countmachine 回答:用C语言进行按位运算

uint64_t set_bit(uint64_t x,int pos,bool value)
{
    // check range
    if (pos<0 || (pos&0x40))
      return 0; // error
    return ((x &~((uint64_t)1<<pos)) | ((uint64_t)value<<pos));
}
,
uint64_t set_bit(uint64_t x,bool value)
{
    if(pos < 0 || pos > 64)
    {
        return x;
    }

    if(value)
    {
        return x | (((uint64_t)1) << (pos - 1));
    }
    else
    {
        return x & (~(((uint64_t)1) << (pos - 1)));
    }
}
本文链接:https://www.f2er.com/3032458.html

大家都在问