访问char中的位?

时间:2013-10-09 23:31:25

标签: c char bit

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

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

我当然不是在找人做我的任务,我只是需要帮助才能获得这一点。我偶然发现了Access bits in a char in C 但似乎该方法只显示了如何获得最后两位。

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

1 个答案:

答案 0 :(得分:3)

修改:根据Chux的评论进行更改。还介绍了旋转位的rotl函数。最初的重置功能是错误的(应该使用旋转而不是shift 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;
}