Forgot your password?
typodupeerror
Programming

Journal tomhudson's Journal: Use a union instead of bit-shifts and bitwise ANDs ... 18

I was looking at the code that does IP address manipulation, and said to myself "These macros suck!"

4 different macros, one to extract each dot-quad digit, from the 32-bit unsigned raw value.

I came up with a quicker, simpler, and (I think) better way, using a union. I gave a quick walk-through to a co-worker today and he likes it ... I mean, REALLY LIKES IT!.

I've posted the description and code here

The code is simple - one struct, one union. The best part is that, unlike the macros, that used shifts and ANDS, this is reversible - assign a 32-bit value, extract the 4 bytes; assign the 4 bytes, extract the 32-bit value.

Its written for little-endian cpus (little end | lowest byte comes first in ram - eg x86) - a simple #ifdef can handle different architectures, if you're ambitious. Post your comments, rate it, tell the world I'm an ID-10-T :-)

This discussion has been archived. No new comments can be posted.

Use a union instead of bit-shifts and bitwise ANDs ...

Comments Filter:
  • and, email addy ideas back to you:

    kingtroll@...

    ventriloquist@... (just don't offer to shake hands after posting...)

    ogregrunt@...

    imunderstood@...

    opinionsbelong@...

    fartback@...

    youbelong@...

    noplaceforwimps@...

    sensitivitiescrushed@...

    battlescarred@...

    If nothing else, the above should cue up a myriad of other ideas...
    I'd like roaringback@... myself. :-b,,,
    • ... and the obvious if you like kids' movies - shrek AT trolltalk.com and fiona AT trolltak.com :-)

      • by RM6f9 ( 825298 ) *
        Shrek and Fiona are ogres - the name of the site is trolltalk (accompanied by small-child exasperation eye-rolls)... just make sure the site isn't invaded by people who like to fish while the boat is moving slowly dragging bait on extended lines behind it... popgear@, spoon@, rainbowtrout@ driftingonin@, etc...,
        (capcha irony:"quaint")
  • Uniona make the code I'm reading so much cleaner. Lot's of bit shifting is closer to obfuscation because there's some dance that needs to be done either in one's head or a piece of paper to figure out what the hell is going on.

    It's like good coffee vs. brown bitter water that's passed off as coffee.

    ARINC429 and even 1553 messages just flow out info so much smoother when picked apart in unions.

    ADA kind of has unions, except that ADA's meaning of existence is to make such transformations take at least 5 step
    • Surprisingly enough, a lot of programmers sort of "glossed over" unions. Not seeing any immediate use for them, they do things the hard way.

      A good example is from c++ - most Point classes have a method - move - that changes the x and y coordinates. Much easier to just pack it into a union (for example, 2 shorts), and add or subtract an int from it that itself is composed of 2 shorts, for the changed directions. Expand this example to a Rect, and you can set all 4 coordinates with 1 8-byte write.

      You cou

  • ...if not exactly new. It definitely makes the code clearer, in my opinion. I'm not sure whether or not it actually saves cycles. That might depend on the hardware and the compiler implementation.

    Oh, and for an email address, you might try billygoatse@... or billygoatse.gruff@...
    • Having glanced through the x86 repertoire, I bet you could save a lot of time if the information is aligned so that you can use the various byte operations.
      Of course, if you're going to get that groovy, why not cut to assembly? That's the supreme method for pissing off the higher-level language snobs. ;)
      • I'd do that all the time with bc++ - use a function call as a wrapper for an assembly routine. It made writing code a lot more fun. It also allowed me to exceed the benchmarks on the label of my (old 80 meg caviar way back when) hard drive by a factor of 2 when it came to large reads.

        Of course, finding an employer that wants that sort of stuff on a day-to-day basis ... that's another story, unless they're a hardware manufacturer.

    • I'm glad you like it. I figure it might or might not save cpu cycles, but it will definitely save grey matter cycles, and they're a LOT more expensive. Its not like I can just swallow another stick of ram and exchange my "twin lobes/dual core" for a quaddie - at least not yet :-)

      What gets me is that this is SO simple, and yet I see the bit and byte-slicing macros in c code everywhere.

      I figure that I'll use trolltalk.com as a sort of "repository" for tricks like that (in the various programming language

  • i hate bit shifting. this is efficient, clean and something i'd rather read on a code review then the way you described it as being implemented before.

    no need to so hard on yourself, you caught something ugly, made it pretty and then were nice enough to share it.

    an idiot would have the mindset oh well it works, so what if its convooluted and sucks, leave it to the next person to deal with. i would more than likely be that person since i did a lot of maintenance to get promotions.
  • The winsock.h implementation that came with Microsoft Visual Studio (which is already at least 9 years old) includes the same structure, and by the tone of their comments I think it was lifted straight from the original Berkeley code from about 1983:

    From winsock.h:

    /*
    * Internet address (old style... should be updated)
    */
    struct in_addr {
    union {
    struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
    struct { u_short s_w1,s_w2; } S_un_w;
    u_long S_addr;
    } S_un;
    #define s_addr S_un.S_addr
    /

    • Nope, no plagarism involved, and normally I don't do Windows (bring a wheelbarrow of money and we'll talk ;-).

      However, as you point out, your post is from winsock.h, which had to keep combatibility with 16-bit code - hence the two shorts. On 16-bit platforms, a short == an int; on 32-bit platforms, a long == an int, so happily, if you declare the whole thing as a long, it works for both.

      Time to rework the standard names ... when 128-bit cpus become mainstream in another 15 years, its going to be awkwar

      • by plover ( 150551 ) *
        Sorry, I wasn't trying to accuse you of anything. I'm just pointing out that unions have been used for this precise function for quite a long while, and that you were on a track that others also consider a good idea.

        BTW, I find unions quite useful when dealing with messaging protocols.

        • I know you wouldn't ever do that - I just wanted to make it clear to anyone else reading the thread that there was no hanky-panky :-)

          I don't know which is more under-used for "weird stuff" - unions or the comma operator ...

If you think nobody cares if you're alive, try missing a couple of car payments. -- Earl Wilson

Working...