Thread: hton

  1. #1
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    404

    hton

    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.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    htonl should involve two calls to htons. One with the upper 16 bits and one with the lower 16 bits. Then reconstruct the result with those answers the other way around.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. hton long long
    By carrotcake1029 in forum C Programming
    Replies: 1
    Last Post: 06-01-2008, 08:26 PM