Bitwise logic operations are used to implement bitwise vectors.

Source: Internet
Author: User

Bitwise logic operations are used to implement bitwise vectors. These operations are used to set, clear, and detect bitwise vectors.

The Code is as follows:

private const int bitsPerWord = 32;private const int shift = 5;private const int mask = 0x1F;private const int n = 10000000;private static readonly int[] a = new int[1 + n / bitSperWord];void set(int i){    a[i >> shift] |= (1 << (i & mask));}void clr(int i){    a[i >> shift] &= ~(1 << (i & mask));}int test(int i){    return a[i >> shift] & (1 << (i & mask));}

The function we implement is to specify an integer (32-bit) array, input a parameter I, set the I bit of the array to 1, or clear the I bit, or the I-bit value.

This Code uses too many bit logic operations, and is not easy to understand.

I> shift

In fact, I is divided by 32, that is, 2 ^ 5. The purpose is to find out where I should be in the array.

1 <(I & mask)

I & mask first calculates the number of digits that should be moved to the left, and then moves 1 to the left. The rest is the element in the array or the operation, or the operation.

In fact, we can better understand these terms.

void set(int i){    a[i / 32] |= (1 << (i % 32));}void clr(int i){    a[i / 32] &= ~(1 << (i % 32));}int test(int i){    return a[i / 32] & (1 << (i % 32));}

Bit vectors have good performance and memory advantages in some specific massive data processing applications (such as searching and sorting.

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.