user1730056
user1730056

Reputation: 623

Accessing the bits in a char?

I have experience with Java and Python, but this is my first time really using C, for my first assignment also haha.

I'm having trouble figuring out how to convert an unsigned char to a bit, so I would be able to get/set/swap some bit values.

I'm not looking for someone to do my assignment of course, I just need help accessing the bit. I came across this Access bits in a char in C But it seems like that method only showed how to get the last two bits.

Any help or guidance is much appreciated. I tried Googling to see if there was some sort of documentation on this, but couldn't find any. Thanks in advance!

Upvotes: 1

Views: 3463

Answers (1)

Igor Popov
Igor Popov

Reputation: 2620

Edit: Made changes in accordance with Chux's comment. Also introduced rotl function which rotates bits. Originally reset function was wrong (should have used the rotation instead of 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;
}

Upvotes: 4

Related Questions