1.6.2 How to Use bitwise logical operations (such as And, Or, displacement) to implement bitwise vectors?

Source: Internet
Author: User

/* How to Use bitwise logical operations (such as And, Or, displacement) to implement bitwise vectors?
It refers to setting, resetting, and testing bitvectors.
Understanding:
Error: an int is used to represent one digit.
It should be an operation bit, but the length may not be a multiple of 8 or 32. Therefore, multiple consecutive bit storages are used, but bit operations are still required.
Error: % is used as the selected location
Cannot Use %,K divided32. You can use the right shift method.
Modulo? K mod 32?
2012.1.6
*/

# Include <stdio. h>
# Include <memory. h>

# Deprecision maxa 1000
# Define leng_int 32
# Define shift 5 // result of division, divided by 32
# Define mask 0x1f // modulo, modulo 32

Int bitvector [1 + maxa/leng_int];

Int islegial (int K)
{
If (k <0 | K> maxa)
Return 0;
Return 1;
}

Void inita ()
{
Memset (bitvector, 0, sizeof (bitvector)/leng_int );
}

Void set (int K)
{
Bitvector [k> shift] | = 1 <(K & Mask );
}
Void clear (int K)
{
Bitvector [k> shift ~ (1 <(K & Mask ));
}
Int test (int K)
{
Return bitvector [k> shift] & (1 <(K & Mask ));
}
Void show ()
{
Int I;
For (I = 0; I <(1 + maxa/leng_int); ++ I)
{
Printf ("% d", bitvector [I]);
}
Printf ("\ n ");
}
Int main ()
{
Inita ();
Show ();
Set (2 );
Show ();
Printf ("Test Result: % d \ n", test (2 ));

Clear (2 );
Show ();
Printf ("Test Result: % d \ n", test (2 ));
Return 0;
}

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.