編集: 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;
}