Java bit operations

Source: Internet
Author: User
Tags binary to decimal bitwise operators decimal to binary

Java bit operations

Bit operations are binary operations that are directly supported by the CPU. Therefore, bit operations have high efficiency. In some cases, proper application of bit operations will have high performance. Usually some encryption algorithms and graphic algorithms use in-place operations.
Java bit Operators
Bitwise operators are used to perform binary bitwise operations. Java provides bitwise operators as shown below:
Bitwise operator (>>,<, >>>,&, |, ^ ,~ ), In the bitwise operator, ~ The others are binary operators. The operation data can only be integral and character data.
1. Basic Knowledge
Complement
All Integer types (except char) are signed integers. This means they can both represent positive numbers and negative numbers. Java uses complement code to show the binary number. In the complement code table, the highest bit is the symbolic bit, the positive number is 0, and the negative number is 1. The Code population rules are as follows:
For the positive number, the maximum bit is 0, and the number of other data replicas is indicated in binary notation. For example, the complement code of + 42 is 00101010.
For a negative number, the bitwise side of the complement code of this number is reversed, and then 1 is added to the entire number, that is, the complement code of this number is obtained. For example, if the value of-42 is 11010110 (00101010, the bitwise result is 11010101 + 1 = 11010110)
The complement code is used to show the number. The complement code of 0 is the only one, and all are 00000000. (In the original code and reverse code table, the tables of + 0 and-0 are not unique. You can refer to the corresponding books ). And can be expressed as-1 in 111111 (this is also the difference between the complement code and the original code and the anti-code ).

* Type Length
Integer
The integer constant occupies 32 places in the machine and has an int value. For a long value, add L or l after the number, for example, 123L indicates a long integer, which occupies 64 bits in the host. There are four types of Full-type variables: byte, short, int, and long. The following lists the number of inner bits of each type and their table dimensions.
Number of digits in the data type description
Integersbyte Byte-length integer 8-bit two's complement
Short Short integer 16-bit two's complement
Int Integer 32-bit two's complement
LongLong integer 64-bit two's complement
Real numbers
Float Single-precision floating point 32-bit IEEE 754
Double Double-precision floating point 64-bit IEEE 754.
Other types
Char A single character 16-bit Unicode character
Boolean A boolean value (true or false) true or false
Int type is the most commonly used Integer type. It indicates that the data range is large enough and is suitable for 32-bit and 64-bit processors. However, for maxcompute, a large integer usually exceeded the range shown in the int type table. In this case, the long type is used.
The storage methods for data stored by machines with different characters are different. The storage mode may be from the low-node to the high-node storage, it may also be stored from a high-text section to a low-text section. In this way, in the case of network analysis agreement or text format, in order to solve the problem of sequential storage in different node storage on the machine, it is appropriate to use the byte type to display data. In general, because the data range shown in the table is small, it is easy to overflow and should be avoided for use.
The short type is rarely used. It limits the storage of data to the first high-character section and then the lower-character section, which may cause errors in some machines.
The definition of integer variation, for example:
Byte B; // specify the variable B as the byte type.
Short s; // specify the variable s as the short type.
Int I; // specifies that the variable I is of the int type.
Long l; // specify the variable l as the long type
Floating Point (real) data
There are two types of real-type variables: float and double. The following table lists the number of BITs occupied by the two types of classes and their representation
Perimeter.
The number of digits occupied by the Data Type
Float 32 3.4e-038 ~ 3.4e + 038
Double 64 1.7e-308 ~ 1.7e + 308
Double precision double type has higher precision and greater table Display dimensions than single precision float type, which is often used.
(3) determine the actual variable volume, as shown in figure
Float f; // The variable f is of the float type.
Double d; // The variable d is of the double type.
[Note] Unlike C and C ++, Java does not have an unsigned integer, and it clearly defines the integer and floating point data.
The number of memory segments ensures the security, robustness, and non-interconnectivity of the platform.

2. Java bitwise operators
Bitwise operators defined by Java performs operations on digits of the integer type directly. These integer types include long, int, hort, char, and byte. Table 4-2 lists bitwise operations:
Operator result
~ Bitwise non (NOT) (mona1 Operation)
& Bitwise AND (AND)
| Bitwise OR (OR)
^ XOR)
> Right shift
>>> Right shift: The left blank space is filled with 0; unsigned right shift
<Move left
& = Bitwise AND value assignment
| = By bit or value
^ = By-bit variance or value assignment
>>= Right shift value
>>>= Shifts the value to the right. The blank places on the left are filled with 0; unsigned values are shifted to the left.
<= Left shift assignment

3. Detailed explanation
1. Non-(NOT) by bit)
Bitwise is also called complement. The unary operator NOT "~" Returns the inverse of each bit of the number of operations. For example, if the number is 42, its binary code is:
00101010
After bitwise non-calculation
11010101
2. bitwise AND (AND)
Bitwise AND operator "&". If the number of both operations is 1, the result is 1. In other cases, the result is zero. See the following example:
00101010 42 & 00001111 15
00001010 10
3. bitwise OR (OR)
Bitwise OR operator "|". If any operation is 1, the result is 1. The following is an example:
00101010 42 | 00001111 15
00101111 47

4. bitwise XOR (XOR)
Bitwise XOR or operator "^", the result is 1 only when two comparison bits are different. Otherwise, the result is zero. The following example shows the effect of the "^" operator. This example also shows a useful property of the XOR operator. Note that the second operation number has a digit of 1, and 42 corresponds to the corresponding bit of binary code. The second operation has a digit of 0, and the number of digits corresponding to the first operation remains unchanged. When bitwise operations are performed on some types, you will see the usefulness of this attribute.
00101010 42 ^ 00001111 15
00100101 37
Application of bit logical operators

The following example illustrates the bit logical operators:

// Demonstrate the bitwise logical operators.
Class BitLogic {
Public static void main (String args []) {

String binary [] = {0000,000 1, 0010,001 1, 0100,010 1, 0110,011 1, 1000,100 1, 1010,101 1, 1100,110 1

};
Int a = 3; // 0 + 2 + 1/0011 in binary
Int B = 6; // 4 + 2 + 0 or 0110 in binary
Int c = a | B;
Int d = a & B;
Int e = a ^ B;
Int f = (~ A & B) | (&~ B );
Int g = ~ A & 0x0f;

System. out. println (a = + binary [a]);
System. out. println (B = + binary [B]);
System. out. println (a | B = + binary [c]);
System. out. println (a & B = + binary [d]);
System. out. println (a ^ B = + binary [e]);
System. out. println (~ A & B | &~ B = + binary [f]);
System. out. println (~ A = + binary [g]);

}
}

In this example, the combination of the corresponding bits of variable a and variable B represents the four combination modes of binary numbers: 0---0, and 1-1. The "|" operator and the "&" operator calculate the corresponding bits of variable a and variable B to obtain the values of variable c and variable d. The assignment of variables e and f illustrates the functions of the "^" operator. The string array binary represents the binary value between 0 and 15. In this example, the binary code of the values corresponding to the variables is displayed in the order of the elements in the array. The array is constructed in this way because the binary code corresponding to the value n of the variable can be correctly stored in the binary [n] element of the array. For example, if the value of variable a is 3, its binary code is stored in the array element binary [3 .~ The value of a and the number 0x0f (corresponding to binary 0000) are bitwise AND calculated to reduce ~ A value to ensure that the result of variable g is smaller than 16. Therefore, the running result of this program can be represented by elements corresponding to the array binary. The output of this program is as follows:

A = 0011 B = 0110 a | B = 0111 a & B = 0010 a ^ B = 0101 ~ A & B | &~ B = 0101 ~ A = 1100

5.

Left Shift Operator
Shift left operator <indicates the number of times that all bits of the specified value are moved left. Its common format is as follows:

Value <num
In this example, num specifies the number of digits to move the value. That is, the Left shift operator <shifts all bits of the specified value to the num bits left. Each time one bit is moved to the left, the higher bit is removed (and discarded), and 0 is used to fill the right. This means that when the number of operations to move left is int type, every 31st bits to move one bit will be removed and discarded; when the number of operations to move left is long type, every time one bit is moved, its 63rd bits will be removed and discarded.
Be careful when performing shift operations on values of the byte and short types. Because you know that Java will automatically extend these types to int type when evaluating expressions, and the expression value is also int type. The result of the shift operation on values of the byte and short types is int type. If the left shift does not exceed 31 bits, the original values will not be discarded. However, if you perform a shift operation on a negative byte or short value, after it is extended to the int type, its symbols are also extended. In this way, the result of the integer value is filled with 1. Therefore, in order to get the correct result, you must discard the high level of the result. The simplest way to do this is to convert the result to the byte type. The following program illustrates this:

// Left shifting a byte value.
Class ByteShift {
Public static void main (String args []) {
Byte a = 64, B;
Int I;
I = a <2;
B = (byte) (a <2 );
System. out. println (Original value of a: + );
System. out. println (I and B: + I ++ B );
}
}

The output of this program is as follows:

Original value of a: 64
I and B: 256 0

The variable a is extended to the int type in the value assignment expression. 64 (0100 0000) is shifted left twice and the generated value 256 (10000 0000) is assigned to the variable I. However, after the Left shift, the only 1 in variable B is removed, and the low position is all 0, so the value of B is also changed to 0.

Since each left shift can double the original operand, programmers often use this method to quickly multiply 2. But be careful, if you move 1 to a higher-order bit (31 or 63 digits), the value will change to a negative value. The following program illustrates this:

// Left shifting as a quick way to multiply by 2.
Class MultByTwo {
Public static void main (String args []) {
Int I;
Int num = 0 xFFFFFFE;

For (I = 0; I <4; I ++ ){
Num = num <1;
System. out. println (num );
}
}
The program output is as follows:
536870908
1073741816
2147483632
-32

The initial value is carefully selected so that it will generate-32 after four digits are shifted to the left. As you can see, when 1 is moved to 31 bits, the number is interpreted as a negative value.

6.

Right Shift Operator
Right Shift Operator> specifies the number of times that all bits of the specified value are shifted to the right. Its common format is as follows:
Value> num
Here, num specifies the number of digits to move the value. That is, the right shift operator> shifts all bits of the specified value to the right. The following program segment shifts the value 32 to the right twice and assigns result 8 to variable:
Int a = 32;
A = a> 2; // a now contains 8

When some bits in the value are "removed", the values of these bits are discarded. For example, the following program fragment shifts 35 twice to the right, and its two low positions are removed and discarded, and result 8 is also assigned to variable:
Int a = 35;
A = a> 2; // a still contains 8
The following code uses binary to indicate the running process of the program:
00100011 35
> 2
00001000 8

Moving the value to the right is equivalent to dividing the value by 2 and dropping the remainder. You can use this feature to quickly divide an integer by two. Of course, you must ensure that you do not remove any of the original digits of the number.
When the right shift is performed, the highest bit (leftmost bit) to be removed is supplemented by the number of the original highest bit. For example, if the value to be removed is a negative number, each right shift is supplemented with 1 on the left. If the value to be removed is a positive number, each right shift is supplemented with 0 on the left, this is called the sign extension (retain the sign bit), which is used to maintain a negative number during the right shift operation. For example, if-8> 1 is-4, the binary representation is as follows:
11111000-8> 1 11111100-4

An interesting problem to note is that because the symbol bit extension (reserve the symbol bit) fills in 1 at a high position each time, the result of-1 right shift is always-1. Sometimes you do not want to retain the symbol when moving the right. For example, the following example converts a byte value to a hexadecimal value. Pay attention to the bitwise and operation of the value after right shift and 0x0f, so that you can discard any symbol-bit extension so that the obtained value can be used as the subscript of the defined array, in this way, the hexadecimal characters represented by the corresponding array elements are obtained.

// Masking sign extension.
Class HexByte {
Static public void main (String args []) {

Char hex [] = {
'0', '1', '2', '3', '4', '5', '6', '7 ',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'f''
};
Byte B = (byte) 0xf1;
System. out. println ("B = 0x" + hex [(B> 4) & 0x0f] + hex [B & 0x0f]);

}

}

The output of this program is as follows:

B = 0xf1

7.

Unsigned right shift
As we can see above, every right shift,> the operator always automatically uses its previous highest bit to fill its highest bit. In this way, the original value symbol is retained. But sometimes this is not what we want. For example, if the number of shifts is not a numeric value, you do not want to extend the number of signs (reserve the number of signs ). This situation is quite common when you process pixel values or graphs. In this case, no matter what the initial value of the number of operations is, you want to add 0 at the highest (leftmost) position after the shift. This is what people call unsigned shift ). In this case, you can use the unsigned right shift operator of Java >>> to always add 0 to the left.

The following program section describes the unsigned right shift operator >>>. In this example, variable a is assigned a value of-1, which is expressed in binary as 32 bits and all values are 1. This value is then moved to the right by the unsigned 24 bits. Of course, it ignores the extension of the symbol bit and always fills in 0 on its left. The value 255 is assigned to variable.

Int a =-1; a = a >>> 24;

The following describes the operation in binary format:

11111111 11111111 11111111 11111111 int-1 binary code >>> 24 unsigned shifts right 24-bit 00000000 00000000 00000000 11111111 int 255 binary code
The unsigned right shift operator >>> is only meaningful to 32-bit and 64-bit values, so it is not as useful as you think. Because you must remember that the value that is too small in the expression is always automatically extended to the int type. This means that the extension and movement of the symbol bit always occur in 32 bits instead of 8 bits or 16 bits. In this way, it is impossible to perform the unsigned movement of the 7th-bit byte value starting with 0, because in the actual moving operation, the expanded 32-bit value is operated. The following example illustrates this:

// Unsigned shifting a byte value.
Class ByteUShift {
Static public void main (String args []) {
Int B = 2;
Int c = 3;

A | = 4;
B> = 1;
C <= 1;
A ^ = c;
System. out. println (a = + );
System. out. println (B = + B );
System. out. println (c = + c );

}
}

The program output is as follows:

A = 3
B = 1
C = 6

8.

Summary of the java shift operation:

1. For the Left shift operation, the higher order bits are removed (and discarded) and filled with 0 to the right. This means that when the number of left-shifted operations is of the int type, every time one bit is moved, its 31st bits will be removed and discarded; when the number of left-shifted operations is of the long type, every time one bit is moved, its 63rd bits will be removed and discarded.

2. The left shift can double the original operand. programmers often use this method for Fast Multiplication of 2. But be careful, if you move 1 to a higher-order bit (31 or 63 digits), the value will change to a negative value.

3. during the shift operation on values of the byte and short types, Java will automatically extend these types to the int type, and the value after the shift is also the int type; if the left shift does not exceed 31 bits, the corresponding values will not be discarded. However, if you perform a shift operation on a negative byte or short value, after it is extended to the int type, its symbols are also extended, the result is filled with 1. Therefore, in order to get the correct result, you must discard the high level of the result. The simplest way to do this is to convert the result of the shift operation to the byte type.

4. Each right shift is equivalent to dividing the value by 2 and discarding the remainder. You can use this feature to quickly divide an integer by two. Of course, you must ensure that you do not remove any of the original digits of the number.

5. The difference between the unsigned right shift (>>>) and right shift:

(1) Each right shift,> the operator always automatically uses its previous highest bit content to fill in its highest bit. In this way, the original value symbol is retained.

(2) The value of the unsigned movement is always 0 at the high position (leftmost.

6. unlike C and C ++, Java does not contain unsigned integers and specifies the memory bytes occupied by integer and floating point data, this ensures security, robustness, and platform independence.
9.

Others:
(1) BCD code (Binary to decimal)

People are usually used to the decimal number, while the computer usually uses binary to represent and process numerical data. Therefore, when the computer inputs and outputs data, it is necessary to convert from decimal to binary.

Each digit of the Decimal number is encoded in Binary format. It is called the Decimal number of Binary encoding, that is, Binary to Decimal or BCD (Binary Coded Decimal) encoding.

There are many BCD encoding methods, usually using 8421 encoding. This encoding method is the most natural and simple. The four-digit binary number is used to represent a decimal number. The weights of each digit from left to right are 23, 22, 21, and 20, respectively, that is, 8, 4, 2, and 1. For example, the decimal number is 1975.

1975 (D) = 0001 1001 0111 0101 (BCD)
Four-digit binary represents six more States in decimal notation. These redundant status codes are known as invalid codes in BCD codes. The conversion between the BCD code and the binary code is not directly carried out. To convert the BCD code into a binary code, you must first convert the BCD code into a decimal code, and then convert it into a binary code; to convert a binary code to a BCD code, convert the binary code to a decimal code before converting it to a BCD code.
10.
(2) character encoding

When processing non-numeric text and other symbols in a computer, you must first digitize them, that is, use binary encoding to represent the text and symbols. Character encoding refers to the character set corresponding to binary numbers. Currently, the most common character set is ANSI, And the binary encoding corresponding to the ANSI character set is called ANSI code, both DOS and Windows use ANSI codes. During the input process, the system automatically converts various types of user input data into binary data and stores the data in computer storage units. During the output process, then, the system automatically converts binary encoded data into a data format that can be recognized by the user and outputs it to the user.
(3) ASC Ⅱ code
Encoding of a character in a seven-bit binary format. A single byte is used to represent a special character. The Byte height is 0 or is used for verification during data transmission. The appendix is the standard asc ii code table.

 

 

Related Article

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.