To further my knowledge of bitshifting, I decided to rewrite htons/htonl.
htons was easy. Only two bytes. Keep in mind I am not checking for endianness yet, I am just getting the byte reversing down.
Code:
unsigned short htons (unsigned short hostshort)
{
return (hostshort << 8) | (hostshort >> 8);
}
Then I went to tackle htonl, and it was a bit tougher.
Code:
unsigned long htonl (unsigned long hostlong)
{
return (hostlong << 16) | (hostlong >> 16);
}
If I feed it 0x11223344, it comes out 0x33441122. I have tried for a while now and cannot understand how to get it to finish the reverse. The closest I got was with this line (I know, get pretty messy):
Code:
(((hostlong << 16) << 8) | ((hostlong << 16) >> 8)) | (((hostlong >> 16) << 8) | ((hostlong >> 16) >> 8));
Can anyone help me with thinking logically about this. I just seem to be at a block.