【问题标题】:Accessing the bits in a char?访问字符中的位?
【发布时间】:2013-10-17 13:16:01
【问题描述】:

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

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

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

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

【问题讨论】:

标签: c char bit


【解决方案1】:

编辑:根据 Chux 的评论进行了更改。还介绍了旋转位的rotl 函数。原来reset函数错了(应该是用旋转而不是移位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;
}

【讨论】:

  • 谢谢,比我想象的要简单
  • 我的函数必须采用 (unsigned char c, int n),我将如何使用 int 而不是 unsigned char for n 来处理这些
  • @user1730056 您可以使用与int 相同的代码。但是,最好使用char,因为int 在大多数架构上要么是2 字节要么是4 字节,而且实际上并不需要那么多空间。由于您最多可以移动 8 位(因为您将值分配给 char),因此 8 位足以表示该值
  • @Robin 奇怪的选择使用基于 1 的索引而不是 0。
  • 酷。想法:reset() 的惯用替代方案。 unsigned char mask = ~(1u &lt;&lt; n); return c &amp; mask;
猜你喜欢
  • 2014-05-12
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多