search
HomeJavajavaTutorialJava bit operation sample code analysis

Bit Operation

I learned bit operation a long time ago, but I haven’t used it for a long time, and I feel like I have almost forgotten it. I recently looked at a few codes for bit arithmetic and found that I couldn’t understand them all, haha. It’s time to come back and catch up on the basics.

All numbers in the program are stored in binary form in computer memory. Bit operations are to directly operate on the binary bits of integers in memory.

Operators for bit operations:

##>> ;>Unsigned right shift

These are very basic knowledge, but if you don’t use it for too long, you will inevitably forget it. You can use it more while coding!

Talk is cheap, show me the code.

Note: It is really difficult to see the application when discussing these alone. If there is anything unclear You can check out other people’s summaries.

Let’s take a look at the application of bit operations with a code:

public final void writeInt(int v) throws IOException {
	  out.write((v >>> 24) & 0xFF);
	  out.write((v >>> 16) & 0xFF);
	  out.write((v >>>  8) & 0xFF);
	  out.write((v >>>  0) & 0xFF);
	  incCount(4);
}

This code is a method in the DataOutputStream class, used to convert an int type integer Write to the stream. The naming of this method is very interesting. It is completely different from the public abstract void write(int b) throws IOException in OutputStream. The parameters of this method seem to indicate that it can write an integer to the stream, but the function of the method is not guessed, but depends on the description of the method.

public abstract void write(int b) throws IOException

Introduction in API:

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

it It is to write a specific byte into the stream. We know that an int type variable occupies 32 bits and a byte occupies 8 bits, so an int type integer less than 256 (2^8) and the last 8 bits of the byte type integer are identical.

So this method is to write the lowest 8 bits of an int variable and ignore the remaining 24 bits. Be extra careful when using this method!

The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

So, writing an int type variable completely into the stream is not a very simple problem. Let's go back to the code above: It is written four times in a row, each time writing one byte of data. In this way, an int type variable is turned into 4 bytes and written into the stream.

out.write((v >>> 24) & 0xFF); This method is to write the lower 8-digit number above, and this specific implementation is corresponding Provided by subclasses.

Let’s take a look at the diagram: A simple AND operation: It can be seen that the result of the operation retains the lower 8 bits, which is (v>>>24) & 0xFF The result of the operation.

Java bit operation sample code analysis

So how to get the high 8-bit value? This requires the use of shift operations:

Java bit operation sample code analysis

By performing the shift operation, you can obtain each 8-bit data, and then perform the bitwise AND & operation, You can completely write an integer into the stream.

Code Demonstration

Code
package dragon;

/**
 * 分析这一个方法,目前水平有限,先从最简单的做起!
 * */

//		   public final void writeInt(int v) throws IOException {
//        out.write((v >>> 24) & 0xFF);
//        out.write((v >>> 16) & 0xFF);
//        out.write((v >>>  8) & 0xFF);
//        out.write((v >>>  0) & 0xFF);
//        incCount(4);
//    }


//上面这段代码是将一个32位整型,写入输出流。
//并且是将32位整型分为4个部分,每次写入8位。
//这是Java的特性。


public class DataOutputStreamAnalysis {
	public static void main(String[] args) {
		DataOutputStreamAnalysis analysis = new DataOutputStreamAnalysis();
		analysis.analysis(65535);
	}
	
	public void analysis(int number) {
		int number1, number2, number3, number4;  //后面的数字表示是一个32位整型的第几个8位。
		number1 = (number >>> 24) & 0xFF;    
		number2 = (number >>> 16) & 0xFF;    
		number3 = (number >>> 8) & 0xFF;
		number4 = (number >>> 0) & 0xFF;
		
		
		
		System.out.println(this.format(Integer.toBinaryString(number))+"  原始数据"); 
		System.out.println(this.format(Integer.toBinaryString(number1))+"  原始数据第一个8位");
		System.out.println(this.format(Integer.toBinaryString(number2))+"  原始数据第二个8位");
		System.out.println(this.format(Integer.toBinaryString(number3))+"  原始数据第三个8位");
		System.out.println(this.format(Integer.toBinaryString(number4))+"  原始数据第四个8位");
	}
	
	/**
	 * 输入一个二进制字符串,将其格式化,因为整型是
	 * 占32位的,但是转换成的二进制字符串,并没有32位*/
	public String format(String bstr) {
		int len = bstr.length();
		StringBuilder sb = new StringBuilder(35);
		for (int i = 0; i < 32-len; i++) {
			sb.append("0");
		}
		sb.append(bstr);
		sb.insert(8, " ");
		sb.insert(17, " ");
		sb.insert(26, " ");   //前面插入一个字符后,所有字符的索引都变了!
		return sb.toString();
	}
}
Result

Java bit operation sample code analysis

Explanation: Negative numbers are not considered here The situation is the same, except that the expression of negative numbers is a little more troublesome. As long as you understand positive numbers, negative numbers are not a problem.

Application of bit operations

1. Determine whether the int type variable x is an odd or even number

Perform a bitwise AND operation on the variables x and 1 , if the result is 0, then the variable x is an even number, otherwise it is an odd number.

if (x & 1 ==0) 
	System.out.println("x是偶数");
if (x & 1 == 1) 
    System.out.println("x是奇数");

Explanation: This is still easy to understand, because the final shift of even numbers must be 0. (Binary representation)

2. Take the k-th bit of the int type variable The binary value of the bit.

Expression:

x >> k & 1 (It is recommended to add parentheses to make it clearer.)

3. Change the int type The k-th position 1 of variable Expression:

x = x | (1 4. Clear the k-th bit of the int type variable to 0

Shift 1 to the left by k bits and then invert the result, and then add the result to the variable for logical operation. Then the k-th bit of variable x is cleared to 0, and the other bits remain unchanged. Expression bits:

x = x & ~(1 ##5. Calculate the average of two integers

Expression bits:(x & y) ((x ^ y) >> 1)

6. For an integer x greater than 1 , determine whether x is a power of 2

if (x & (x-1) == 0)
	System.out.println("x是2的次幂");
7. Multiply a number by the nth power of 2

Expression: x = x

For example: expand x by 2 times: x = x

The reason why bitwise operations are recommended:

The speed of bit operations is faster than arithmetic operations, because bit operations require fewer instructions and require less time to execute. They will appear very fast, but the bit operations can only be seen when a large number of executions are performed. Advantages of operations. After all, today's computers are getting faster and faster.

Operator Meaning
& bitwise and
| bitwise or
~ Bitwise negation
^ Bitwise XOR
Shift left
>> Shift right with sign

The above is the detailed content of Java bit operation sample code analysis. 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

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),

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment