Java bitwise operator Instances--with (&), non (~), or (|), XOR (^)

Source: Internet
Author: User

One, the Java bitwise operator Instance--with (&), non (~), or (|), XOR (^)

1, and (&)

0 & 2 = 0

0 0 0
0 1 0
0 1 0

2, non (~)

~0 = 7

0 0 0
1 1 1

3, or (|)

0 & 2 = 2

0 0 0
0 1 0
0 1 0

4, XOR (^)

1 & 2 = 3

0 0 1
0 1 0
0 1 1

Second, the use of the scene. (similar to marking)

 Public enum flagenums {    A (1, "H"),     B (2, "rich"),
C (3, "handsome"),

;
Private intbit; PrivateString desc; Flagenums (intbit, String desc) {         This. bit =bit;  This. desc =desc; }        /*** Gets the value of the current flag decimal * *@return     */     Public LongGetbit2value () {BigDecimal Posvalue=NewBigDecimal (2); Posvalue=posvalue.pow (bit); returnPosvalue.longvalue (); }    /*** Determine if the flag has a * *@paramFlag *@return     */     Public BooleanIsbiton (Longflag) {        if(Flag & Getbit2value ()) = =Getbit2value ()) {            return true; }        return false; }         Public intgetbit () {returnbit; }     Public voidSetbit (intbit) {         This. bit =bit; }     PublicString GetDesc () {returndesc; }     Public voidSetdesc (String desc) { This. desc =desc; }}

User personality tag, we can use Falg value to express, the personality tag combination determines the FALG value. The combination of each label with the operation is the FALG value.

The following three actions are performed on the user:

①, "high" label for users

Flag | Flagenums.a.getvalue ()

②, Erase "high" label to user

Flag & (~flagenums.a.getvalue ())

③, determine if the user has a "high" label

Flagenums.a.isbiton (flag);

Java bitwise operator Instances--with (&), non (~), or (|), XOR (^)

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.