search
HomeJavajavaTutorialWhat are the techniques for java bit operations?

What is bit operation

We all know that the form of data stored in computers is binary data. Bit operation is a method of operating data at the binary level. Bit operation Directly operate on binary data composed of 0 and 1.

Basic bit operations

There are six basic bit operations, namely** AND or NOT XOR shift left and right**

## When both bits # and are 1, the result is 1. or when both bits are 0, the result is 1. 0^XORWhen the two bits are the same, the result is 1, if they are not the same, the result is 0 ~Inversion0 becomes 1, 1 becomes 0##>>
  • ** First of all, it must be clear that bit operations can only operate on integers**

  • In jdk, java right shift is an arithmetic right shift operation

  • ** Bit operations have low priority, so it is best to use parentheses **

What are the techniques for java bit operations?

The output result of the above code:

What are the techniques for java bit operations?

Let’s analyze why this result is output:

  • First of all, for 13 , we write its binary: 0000 1101

  • Shift right by two places: 0000 0011. Since the right shift in jdk is an arithmetic right shift, the high bits are filled with 00, and the result is 3

  • For -13, binary code: 1111 0011

  • Shift right by two bits, high-order complement sign bit, 1111 1100, the result is -4

Commonly used bit operationsTips

Bit operations are often used for some small operations, because they can only operate on integers. numbers, so its uses are limited, but some commonly used tips are worth mastering, such as judging odd and even, exchanging two numbers, exchanging signs, finding absolute values, etc. We will introduce them one by one below.

Judge parity

The difference between parity and evenness is reflected in binary, that is, the end is 0, 1. Obviously, when the end is 0, it is an even number, and when the end is 1, it is the last One odd number. So the way to determine parity is:

What are the techniques for java bit operations?

A small test program:

What are the techniques for java bit operations?

The above program will output all Even numbers within 1000

Exchanging two numbers

The advantage of using bit operations to exchange two numbers is that there is no need for a third temp variable (the limitation is that only integer variables can be exchanged)

What are the techniques for java bit operations?

Analyze how the exchange occurs:
First a^=b, that is, a=(a^b);
b^=a, that is, b= b(ab), since the operation satisfies the commutative law, b(ab)=bb^a. A number that is XORed with itself must be 0, because it must be equal to itself. So if a number is XORed with 0, 1 and 0 will still be 1, and 0 and 0 will still be 0, so obviously a number and 0 After XOR, of course it is still itself. So at this time, b is assigned the value a.
The last step, a^=b is a=ab. Since the previous two steps show that a=(ab), b=a, so a=ab means a=(a b)^a. Therefore, a will be assigned the value of b.

Converting symbols

Converting symbols is obviously very simple. According to the similar complement code, just take the inverse and add one.

What are the techniques for java bit operations?

Finding the absolute value

Finding the absolute value is achieved on the basis of changing the sign. We only need to first determine whether it is a negative number. , if it is a negative number, change the sign, if not, just return it directly.
To determine the positive or negative, you can directly determine the sign bit, shift 31 bits to the right, get the sign bit, and determine the positive or negative

What are the techniques for java bit operations?

##For any number, XOR with 0 will Remaining unchanged, XOR with -1, which is 0xFFFFFFFF, is equivalent to negation. Therefore, the absolute value can also be obtained by XORing a with i and then subtracting i (because i is 0 or -1, so subtracting i means either adding 0 or adding 1). Therefore, the above code can be optimized:


What are the techniques for java bit operations?

Application of bit operations

Common algorithm problems, implementation of bit operations The operation of A and B is a common algorithm problem.

What are the techniques for java bit operations?

#The above code realizes the addition operation of two numbers without using operators and using bit operations.

Now let’s explain the principle of bit operation to add two numbers
First of all, in decimal, we know that, 7 8, the sum without carry is 5, the carry is 1, and then we can use the sum without carry and carry 5 1*10 calculates the final result 15.
This method can also be adopted for similar binary systems
For example,
a = 3, b = 6
a: 0011
b: 0110
Without carry sum: 0101, which is 5
Carry: 0010 which is 2
so a b becomes 5 (25  0101
2No carry and 0001 = 1
Carry 0100 = 4
Therefore a b becomes 1 4 and then there is
1  0001
4 without carry and 1001 = 9
with carry 0000 = 0
When the carry is 0, the sum without carry is 9, which is the sum of a and b.

You can find that the above is a recursive process, so it is not difficult to write the code. Finding the carry-free sum of two numbers is actually just an XOR operation of the two numbers.

Symbol Description Operation rules
&

Shift left Each binary bit is shifted to the left by a certain number of bits, the high bit is discarded, and the low bit is filled with 0
Shift right Each binary bit is shifted to the left by a certain number of bits, the high bit is discarded, and the high bit is filled with the sign bit or zero, depending on the compiler

The above is the detailed content of What are the techniques for java bit operations?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.