Bitwise operations in Java

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

Bitwise operations in Java

 

Java bit operator

Bitwise operators are used to operate binary bits. 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.

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
Integers

Byte byte-Length Integer 8-bit two's Complement

Short short integer 16-bit two's Complement

Int integer 32-bit two's Complement

Long

Long 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 memory types of data stored by machines with different types of data are different. It may be from low-node to high-node storage, or
It may be from a high-node to a low-node storage. In this way, in order to solve the inconsistency between the network and the server
To show data in bytes. In general
Small Scope, easy to overflow, should avoid 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.

Java bit 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)

^
Bitwise exclusive or (XOR)

>
Right Shift

>>>
Right Shift. The left blank places are filled with 0; unsigned right shift

<
Move left

& =
Bitwise AND value assignment

| =
Bitwise OR value assignment

^ =
Bitwise variance or value assignment

>>=
Shift value to the right

>>>=
Shifts the value to the right. The blank places on the left are filled with 0; the unsigned value is shifted to the left.

<=
Left shift assignment

Detailed explanation

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

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

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

Bitwise exclusive or (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", "0001", "0010", "0011", "0100", "0101", "0110", "0111 ", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"

};
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

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.

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

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

Summary of the Java shift operation:

<! -- [If! Supportlists] --> 1. <! -- [Endif] --> 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.

<! -- [If! Supportlists] --> 2. <! -- [Endif] --> the 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.

<! -- [If! Supportlists] --> 3. <! -- [Endif] --> during the shift operation on values of the byte and short types, Java automatically expands 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.

<! -- [If! Supportlists] --> 4. <! -- [Endif] --> every 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.

<! -- [If! Supportlists] --> 5. <! -- [Endif] --> unsigned right shift (>>>:

<! -- [If! Supportlists] --> (1) <! -- [Endif] --> each 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.

<! -- [If! Supportlists] --> (2) <! -- [Endif] --> the value of unsigned movement is always 0 at the high position (leftmost.

<! -- [If! Supportlists] --> 6. <! -- [Endif] --> unlike C and C ++, Java does not have unsigned integers and explicitly specifies the memory bytes occupied by integer and floating-point data, this ensures security, robustness, and platform independence.

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.
(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.

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.