关于将 7 位更改为一个数字并在 c++ 中返回该数字

About change the 7 bit to a number and return that number in c++

本文关键字:数字 一个 c++ 返回      更新时间:2023-10-16
int setBit7to1(int v)
{
    // TODO: set bit 7 to 1
    return v;
}
int setBit5to0(int v)
{
    // TODO: set bit 5 to 0
    return v;
}

例如

  • setBit7to1:如果输入:0x01,则输出:0x81
  • setBit5to0:如果输入:0xffff,则输出:0xffef

有人可以帮忙吗?

如果要将一位设置为 1只需使用此"位 |1"(因为 0 | 1 = 1;1 | 1 =1(

如果要将一位设置为 0只需使用这个"bit & 0"(因为 0 & 0 = 0;1 & 0 = 0(所以,对于你的问题,你可以写这个

int setBit7to1(int v)
{
    return (v | 0x80);
}
int setBit5to0(int v)
{
    return (v & 0xffffffef);//If int is 4 BYTE
}
int setBit7to1(int v)
{
    //here, 7th bit will be or'd with 1( (x | 1) == 1)
    return (v | 0x80);
}
int setBit5to0(int v)
{
    //here, every bit except the 5th bit will be set to itself( (x ^ 1) == x ), 5th bit cleared
    return (v & 0xef);
}
相关文章: