Java Bitwise Operators

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/zhouhaisunny/article/details/102768481

Introduction java bitwise operator

We know that the computer is the underlying binary 0 and 1,00100101 into decimal calculation 1 + 0 + 1 * 1 * 2 ^ 2 ^ 2 + 0 + 0 * 2 ^ 3 ^ 2 * 4 + 1 * 2 5 + 2 ^ 0 * 37 ^ 6 =

1 byte = 8 bytes ( 'bit), the most significant bit is the sign bit, 0 represents a positive one for negative.

1. theoretical definition

(1) the most significant bit is the sign bit, 0 for positive, 1 for negative;

(2) a positive number of the original code, the inverted, complementary codes are the same ;

(3) = negative inverted its original code symbol bits unchanged, the other bit is inverted (0-> 1 0-> 0);

(4) = negative complement its inverse +1; reverse complement code = 1;

(5) anti-complement code 0 is 0;

(6) java no unsigned number, java numbers is signed;

(7) at the time of computing, it is a way to complement arithmetic, so the calculated negative bitwise OR, bitwise AND, bitwise complement after acquisition would have to first XOR decimal arithmetic negative then , the same time, the result is negative tuple (1 ********) is also converted to the inverted, then into the original code.

2 and bitwise shift operators:

Java has four bit operations, namely, "& bitwise and, bitwise or |, ^ bitwise exclusive OR, bitwise ~", which calculation rule:

Bitwise AND &: Two all 1, the result is 1;

Bitwise or |: there is a two to one, the result is 1;

Bitwise XOR ^: only when the number of corresponding bits are not the same, the only takes 1 bit, if the same, that is 0;

Bitwise ~: 0-> 1, 1-> 0

3.Java has three shift operators:

>> arithmetic right shift: low overflow, the sign bit unchanged, and fill overflow with high sign bit

<< arithmetic shift left: the sign bit constant, low fill 0

>>> Logical shift right: low overflow, high fill 0

Example:

示例1:~2:
原数按位取反得到负数元组(补码),所以要转成反码,然后转成原码
原数:00000010
取反:11111101  这个结果是补码
反码:11111100
结果:10000011  结果-3

示例2:2&3
00000010
00000011
结果:00000010  结果:2

示例3:2|3
00000010
00000011
结果:00000011 结果3

示例4:~-5
因为计算机计算都按补码计算,所以先获取-5的补码,然后包括符号位在内全部0变1,1变0,获取结果
原码:100000101
反码:111111010
补码:111111011
结果:000000100 结果:4

示例5:-3^3
-3原码:100000011
      反码:111111100
      补码:111111101
00000011
      结果:11111110(这是补码)
      补码:11111110加上-1的补码111111111结果是1111111101取反100000010 结果-2

Guess you like

Origin blog.csdn.net/zhouhaisunny/article/details/102768481