The methods of several operation bits in C + +

Source: Internet
Author: User
Tags bitset

ReferenceHow does the set, clear and toggle a single bit in C?

The operations on BITS in C + + include setting a bit to 1, clearing a bit (set to 0), switching a bit (toggling a bit), checking if a bit is 1, and so on. These operations are more common and can be used as the underlying interface for other bit operations, and there are several methods listed below:

Traditional methods
    • Set a bit to 1
number |= 1 << x; // 设置第x位为1
    • Clear a bit
number &= ~(1 << x); // 置第x位为0
    • Switch a bit
number ^= 1 << x;
    • Check a bit
if (number & (1 << x))

Accordingly, we can encapsulate it in a convenient way by using a macro to encapsulate:

#define BIT_SET(a,b) ((a) |= (1<<(b)))#define BIT_CLEAR(a,b) ((a) &= ~(1<<(b)))#define BIT_FLIP(a,b) ((a) ^= (1<<(b)))#define BIT_CHECK(a,b) ((a) & (1<<(b)))
Using bit structure operations

This is a lot easier to use:

structBits{UnsignedIntA:1;UnsignedIntB:1;UnsignedIntC:1;};structBitsMybits;Set/clear a bitMybits.B=1;mybits. C = 0; Toggle a Bitmybits. A = ! Mybits. A; Mybits. b = ~mybits. B; Mybits. C ^= 1; Check a bitif  (mybits. C)                
Using STL's Std::bitset

This approach is similar to using a bit structure, except that STL wraps the structure definition and, of course, provides a lot of convenient interfaces:

Std::bitset<5> bits; Bits[0] = true ; bits[1] =  False; Bits. Set (2. Flip (3. Reset (2          

 

The methods of several operation bits in C + +

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.