Table of Contents
Bit Operation
Code Demonstration
Code
Result
Application of bit operations
Home Java javaTutorial Java bit operation sample code analysis

Java bit operation sample code analysis

Apr 23, 2023 pm 01:52 PM
java

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);
}
Copy after login

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
Copy after login

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();
	}
}
Copy after login
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是奇数");
Copy after login

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

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

##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的次幂");
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles