The fastest two-digit exchange in C Language

Source: Internet
Author: User

Self carrying: http://hi.baidu.com/evergreen19/blog/item/dbc1d5f13241c3a5a50f5245.html

Recently started writing, RC4, because a lot of swap is required, so the swapAlgorithmEfficiency has a significant impact on the overall speed of RC4, so we have summarized some good exchange algorithms to share with you.

Int A = 5, B = 7;

Method 1: inline assembly, using the stack zone --Swapping containers

_ ASM {

Push

Push B

Pop

Pop B

}

Method 2: Use the exclusive or operation

A = a ^ B;

B = a ^ B;

A = a ^ B;

Or written:

A ^ = B;

B ^ =;

A ^ = B;

Method 3: Addition Switching

A = A + B;

B = A-B;

A = A-B;

Method 2 and 3 are the same:

Using the nature of inverse functions, functionsC = f (a, B), There must be an inverse function,A = g (C, B );

In this way, you can use

A = f (a, B );

B = g (A, B );

A = g (A, B );

Three-Step exchange of two numbers


Method 4: UseXchgCommand---Use special commands (Dedicated instructions)

_ ASM {

MoV eax,

Xchg eax, B

MoV A, eax

}

However, the Register size must be used, for example:

1,16BitCPUThe data registers include:(Ax,BX,CXAndDX)

2,32BitCPUThe data registers include:(Eax,EBX,ECXAndEDX)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.