How to swap nibbles in C?

后端 未结 4 1835
梦谈多话
梦谈多话 2021-01-07 04:41

How to swap the nibble bit positions of a number?

For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 04:58

    1)

    y = ((x >> 4) & 0x0f) | ((x << 4) & 0xf0);
    

    2)

    unsigned char swap_nibbles(unsigned char c)
    {
         unsigned char temp1, temp2;
    
         temp1 = c & 0x0F;
         temp2 = c & 0xF0;
         temp1=temp1 << 4;
         temp2=temp2 >> 4;
    
         return(temp2|temp1); //adding the bits
    }
    

    3)

    unsigned char nibbleSwap(unsigned char a)
    {
        return (a<<4) | (a>>4);
    }
    

提交回复
热议问题