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.
Then I went to tackle htonl, and it was a bit tougher.
unsigned short htons (unsigned short hostshort)
return (hostshort << 8) | (hostshort >> 8);
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):
unsigned long htonl (unsigned long hostlong)
return (hostlong << 16) | (hostlong >> 16);
Can anyone help me with thinking logically about this. I just seem to be at a block.
(((hostlong << 16) << 8) | ((hostlong << 16) >> 8)) | (((hostlong >> 16) << 8) | ((hostlong >> 16) >> 8));