This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

swap equivelant.

Hi,

Is there an equivelan function or keyword to "swap"? Is there anyway to get the high or lower nibbles of a variable or swap them in C? any help would be appreciated.

-=N

  • I don't think you have direct access to the 8051 swap instruction. It's not one of the intrinsic functions (though it might make a useful addition, perhaps).

    This code will do the job:

    U8 lo = n & 0x0f;
    U8 hi = n >> 4;
    U8 swap = (n << 4) | (n >> 4);

    But you'll have to check the output from the compiler to see if they're clever enough to generate SWAP instructions for that.

    If not, and it's a key part of your project, you could just write your own little assembly function.

    PUBLIC  _swap
    _swap:  MOV A, R7
            SWAP
            MOV R7, A
            RET
    

    Marshalling the argument into R7 and putting it back when you return from the call are probably going to make this more expensive than the (n & 0x0f) operation, at least. Might be a little better than the shifts, if those shifts are taken literally.

    Try an experiment, and let us know what the code looks like.

  • uhhh, well the code doesn't look good. The shift are taken literally and theres two loops in the swap function. I think the assembly function is much faster.

    Regards

    -=N

  • All that would be required is for C51 to detect a special case of the intrinsic function _crol_() when the number of bits to roll is known to be four. e.g.

    	c = _crol_(c, 4);
    
    C51 could then simply use a SWAP. In fact C51 could roll by any number of know bits by simply using a combination of SWAP and no more than two RL or RR instructions.

  • And you know:

    Cole Knows Rolls!

    (Ought to be able to get some sort of Nike or Gatorade endorsement ad outta this somehow.)

  • For some 4-bit shift subexpressions, C51 does optimize and utilize the SWAP instruction. If you are interested, follow this link to some comments I made in another 8051-related forum:

    http://www.8052.com/forum/read.phtml?id=55578