Introduction to bit operations and application scenarios in java
Mar 08, 2021 pm 04:32 PMWe know that all numbers in the program are stored in binary form in computer memory, and bit operations are to directly operate on the binary bits of integers in memory. For example, the and operation is originally a logical operator, but the AND operation can also be performed between integers.
Bit operations mainly include shift operations and logical operations. Next we will talk about shift operations and logical operations respectively.
Shift operation:
Left shift: The operator is <<, move to the left, add 0 to the low bit on the right, discard the high bit on the left, treat binary as an integer, shift left by 1 bit is equivalent to multiplying by 2. Unsigned right shift: The operator is >>>, moving to the right, discarding the right side, and adding 0 to the left side. Signed right shift: The operator is >>, move to the right, and discard the right side. The value added to the left depends on the original highest bit. If it is originally 1, add 1, and if it is 0, add 0. Think of binary as For an integer, shifting it right by 1 bit is equivalent to dividing by 2.
For example:
int a = 4; // 100 a = a >> 2; // 001,等于1 a = a << 3 // 1000,變?yōu)?
Logical operations include:
Bitwise AND&: both bits are 1 to be 1
Bitwise OR|: As long as one bit is 1, it is 1
- ##Bitwise negation~: 1 becomes 0, 0 becomes 1
- bitwise Application scenarios: Scenario 1: Determine parity
int a = ...; a = a & 0x1 // 返回0或1,就是a最右邊一位的值。 a = a | 0x1 //不管a原來最右邊一位是什么,都將設為1Scenario 2: Determine whether a positive integer is an integer power of 2Analysis: Let’s first look at the common integer powers of 2 The numbers: 2, 4, 8, 16, converted into binary are: 10, 100, 1000, 10000. Have you found the pattern? That is, except for the first bit which is 1, the others are all 0. It just so happens that after subtracting 1 from these numbers, they equal the results of their bitwise inversions. For example, 8-1=7, which is 111 in binary, can be obtained by bitwise inverting the binary 1000 of 8. And 8&7=0, extract the rule and it is:
int i = 1;// 二進制存儲方式為00000000000000000000000000000001 int j = 5;// 二進制存儲方式為00000000000000000000000000000101 int k = 6;// 二進制存儲方式為00000000000000000000000000000110 if ((i & j) == 1) { System.out.println("j的最低位為1,為奇數(shù)"); } if ((i & k) == 0) { System.out.println("k的最低位為0,為偶數(shù)"); }The n that conforms to this rule is an integer power of 2. (Learning video sharing:
java video tutorial
)Scenario 3: Simple collection processingNo nonsense, just look at the code:
(n&(n-1))==0Test it:
public class SimpleSet { public static final int A = 0x01;// 最后四位為0001 public static final int B = 0x02;// 最后四位為0010 public static final int C = 0x04;// 最后四位為0100 public static final int D = 0x08;// 最后四位為1000 private int set = 0x00;// 初始0000,空集合 public void add(int i) {// 將i對應位的值置為1,重復add不影響。默認傳入值為ABCD之一,此處省去邊界判斷 set |= i; } public boolean contain(int i) {// 判斷相應位置是否為1 return (set & i) == i; } public boolean remove(int i) {// 來不及不解釋了快看代碼 if (contain(i)) { set -= i; return true; } else { return false; } } }The output is:
public static void main(String[] args) { SimpleSet set = new SimpleSet(); System.out.println(set.contain(A)); set.add(B); System.out.println(set.contain(A)); System.out.println(set.contain(B)); set.add(A); set.add(C); System.out.println(set.contain(A)); set.remove(A); System.out.println(set.contain(A)); System.out.println(set.remove(A)); System.out.println(set.contain(C)); }Okay, no problem. You may think that A, B, C, and D in the above example code are somewhat similar to enumerations. In fact, the collection class EnumSet in the jdk source code for enumerations uses a similar solution. Of course it is much more complicated than this. If you are interested, you can check out the source code. This solution has a name, called bit vector. By the way, there are many static tools in Integer, the packaging class of int in Java, that provide bit operations, and most of them are very complicated. If you are interested, you can take a look.Conclusion: Bitwise operations are the operations that computers are best at, and they are also used extensively in the source code of jdk. Understanding them will help us understand the computer more deeply, and it will also help us write more elegant code. Related recommendations:
java introductory tutorial
The above is the detailed content of Introduction to bit operations and application scenarios in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.
