1

我有使用 Java 和 Python 的经验,但这是我第一次真正使用 C,我的第一个任务也是哈哈。

我无法弄清楚如何将无符号字符转换为位,因此我将能够获取/设置/交换一些位值。

当然,我不是在找人来完成我的任务,我只需要帮助访问该位。我在 C 中的 char 中遇到了这个Access bits 但似乎该方法只显示了如何获取最后两位。

非常感谢任何帮助或指导。我试着用谷歌搜索看看是否有关于这方面的某种文档,但找不到任何文档。提前致谢!

4

1 回答 1

4

编辑:根据 Chux 的评论进行更改。还引入rotl了旋转位的功能。最初的重置功能是错误的(应该使用旋转而不是移位tmp = tmp << n;

unsigned char setNthBit(unsigned char c, unsigned char n) //set nth bit from right
{
  unsigned char tmp=1<<n;
  return c | tmp;
}

unsigned char getNthBit(unsigned char c, unsigned char n)
{
  unsigned char tmp=1<<n;
  return (c & tmp)>>n;
}

//rotates left the bits in value by n positions
unsigned char rotl(unsigned char value, unsigned char shift)
{
    return (value << shift) | (value >> (sizeof(value) * 8 - shift));
}

unsigned char reset(unsigned char c, unsigned char n) //set nth bit from right to 0
{
  unsigned char tmp=254; //set all bits to 1 except the right=most one
//tmp = tmp << n; <- wrong, sets to zero n least signifacant bits
                 //use rotl instead
  tmp = rotl(tmp,n);
  return c & tmp;
}

//Combine the two for swapping of the bits ;)
char swap(unsigned char c, unsigned char n, unsigned char m)
{
  unsigned char tmp1=getNthBit(c,n), tmp2=getNthBit(c,m);
  char tmp11=tmp2<<n, tmp22=tmp1<<m;
  c=reset(c,n); c=reset(c,m);
  return c | tmp11 | tmp22;
}
于 2013-10-09T23:44:31.290 回答