How to swap nybbles in C?

匆匆过客 提交于 2019-12-09 21:10:06

问题


How to swap the nybble 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 then make a new number with that.

Anyone know how to do this?


回答1:


Start from the fact that hexadecimal 0xf covers exactly four bits. There are four nibbles in a 16-bit number. The masks for the nibbles are 0xf000, 0xf00, 0xf0, and 0xf. Then start masking, shifting and bitwise OR-ing.




回答2:


Sean Anderson's bit twiddling guide has the following:

// swap nibbles ... 
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);

under the entry for Reverse an N-bit quantity in parallel in 5 * lg(N) operations.




回答3:


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);
}



回答4:


If swap is more like a 32 bit endiness conversion the below API must work:

uint32 decode_32le(uint8 *p)
{
return ( p[0] | (p[1] << 8) | (p[2] << 16) |(p[3]<<24));
}

*here it will swap the consecutive memory location/bytes which is allocated by malloc/calloc only, not an array.



来源:https://stackoverflow.com/questions/8484188/how-to-swap-nybbles-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!