Java notes: Bit arithmetic

Source: Internet
Author: User
Tags bitwise

First, data storage

The binary number is stored in the form of a complement in memory. The inverse code and the complement of the positive numbers are themselves. The inverse code for negative numbers is the same as the sign bit and the remaining bits are reversed, and the complement is the inverse code +1.

Second, bitwise operations

① bitwise inverse: Reverses all bits in the operand.

② bitwise AND: Only if two operands are 1, the result is 1. Otherwise, it is 0.

③ bitwise OR: As long as there is an operand of 1, the result is 1. Otherwise, it is 0.

④ Bitwise XOR: Only one operand is 1 and the result is 1. Otherwise, it is 0.

⑤ left: Moves all values that do not include the symbol bit to the left by the specified number of times, and adds 0 to the right. Each left shift is equivalent to * *.

⑥ right: Moves all values that do not include the symbol bit to the right by the specified number of times, and adds 0 to the left. Each right shift is equal to/2.

⑦ unsigned Right Shift: moves all values that include the sign bit to the right by the specified number of times, only makes sense for numbers with widths of 32 and 64, and smaller values are automatically promoted.

Iii. examples

classSolution { Public Static voidMain (string[] args) {byteA = 42;//00101010        byteb = 15;//00001111System.out.println (~a);//Bitwise Inverse result is 11010101 complement to 10101011System.out.println (A & B);//bitwise AND result as 00001010System.out.println (A | b);//bitwise OR result is 00101111System.out.println (a ^ b);//Bitwise XOR or result is 00100101        bytec = 64;//01000000System.out.println (c << 1);//Move left 1-bit result to 10000000System.out.println (c >> 1);//Move right 1-bit result to 00100000        intD =-1;//11111111 111111111 111111111 111111111System.out.println (d >>> 24);//unsigned Right shift 24-bit results for 00000000 00000000 00000000 11111111    }}

Java notes: Bit arithmetic

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.