Seek the fastest solution

Source: Internet
Author: User

There are two ulong numbers L1 and L2. You need to set the n-bit (BIT) of L1 to the M-bit (BIT) of L2 ).
For example, L1 is (Binary) 10101000010 ..... (64-bit in total, low-> high), L2 is (Binary) 0101110001 .... (64-bit low-> high in total), set L1 3rd bits (now 1) to L2 1st bits (now 0 ).
I wroteAlgorithmBut it is found that the speed is not fast (used in the encryption algorithm), and most of the time is spent on judgment. I wonder if you can write faster.CodeOr have other optimization skills. The following are my algorithms. Let's take a look at them ~~~ We look forward to your answers. Thank you!

Private   Const Ulong_1 As Ulong =   Ctype ( 1 , Ulong) ' All are 1 ulong
Public   Sub setbit () Sub Setbit ( Byref L1 As Ulong, Byval N As   Integer , Byval L2 As Ulong, Byval M As   Integer )
If (L2 And (Ulong_1 < M )) =   0   Then
L1 = L1 And   Not (Ulong_1 < N)
Else
L1 = L1 Or (Ulong_1 < N)
End   If
End sub

After meditation, the problem is solved: Sub setbit () Sub Setbit ( Byref L1 As Ulong, Byval N As   Integer , Byref L2 As Ulong, Byval M As   Integer )
L2 = (L2 > M) And Culng ( & H1)
L1 = L1 And   Not (Culng ( & H1 < N ))
L1 = L1 + (L2 < N)
End sub

Now it takes only 1000000 ms to execute 31.25 times, and the speed has reached the requirement.
The idea is as follows:
The idea is to shift m in L2 to the rightmost, and then take and with 1, so that M is taken out. For L1, I set N to 0, that is, and 111111 .. 0... 111, 111111 .. 0... 111 comes from 1 <n and then returns the inverse. Finally, we can add the value obtained from L1 to L2 and later.

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.