Home  >  Article  >  Java  >  Detailed explanation of binary and bit operations in Java

Detailed explanation of binary and bit operations in Java

WBOY
WBOYOriginal
2017-07-24 14:07:001937browse

Binary and basic bit operations in Java

Binary is a number system widely used in computing technology. Binary data is a number represented by two digits, 0 and 1. Its base is 2, the carry rule is "every two is forwarded to one", and the borrowing rule is "borrow one to be equal to two", which was discovered by Leibniz, the German master of mathematical philosophy in the 18th century. The current computer system basically uses a binary system, and data is mainly stored in computers in the form of two's complement codes. The binary system in the computer is a very tiny switch, with "on" representing 1 and "off" representing 0.

So what does binary look like in Java? Let us uncover its mysterious veil together.

1. Java’s built-in base conversion

The basic calculation methods of converting decimal to binary and binary to decimal will not be discussed here.

There are several methods built into Java to help us perform various hexadecimal conversions. As shown in the figure below (taking Integer as an example, other types are the same):


1, convert decimal to other bases:

1 二进制:Integer.toHexString(int i);
2 八进制:Integer.toOctalString(int i);
3 十六进制:Integer.toBinaryString(int i);

2. Convert other bases to decimal:

1 二进制:Integer.valueOf("0101",2).toString;
2 八进制:Integer.valueOf("376",8).toString;
3 十六进制:Integer.valueOf("FFFF",16).toString;

3. Use the parseInt() method and valueOf() method in the Integer class to convert other bases to decimal.

The difference is that the return value of the parseInt() method is of type int, while the return value of valueOf() is an Integer object.

2. Basic bit operations

Binary can add, subtract, multiply and divide just like decimal, but it also has a simpler operation method - bit operations. For example, the size of the int type in computers is 32 bits, which can be represented by 32-bit binary numbers, so we can use bit operations to calculate int type values. Of course, you can also use ordinary methods to calculate some data, here I mainly introduce to you the methods of bit operations. We will find that bit operations have incomparable power with ordinary operation methods. For more applications of bit operations, please move to my next blog post "Magic Bit Operations"

First, let's take a look at the basic operators of bit operations:


Advantages:

Under certain circumstances, calculation is convenient, fast, and widely supported

If arithmetic methods are used, the speed is slow and the logic is complex

Bitwise operations are not easy Limited to one language, it is the basic computing method of computers >>>>>>>>>>>>>>>>>>>>>>>>> > >>> , the result is 1

0&0=0; 0&1=0; 1&0=0; 1&1=1

For example: 51&5 is 0011 0011 & 0000 0101 =0000 0001 therefore 51&5=1.

Special Usage

(1) Clear. If you want to clear a cell to zero, even if all its binary bits are 0, just AND it with a value whose bits are all zero, and the result will be zero.

(2) Take the specified position in a number.

For example: Suppose X=10101110, take the lower four digits of X, and use

Method: Find a number that corresponds to the bit that x needs to be. The corresponding bit of the number is 1 and the remaining bits are zero. Perform an AND operation on this number and x to get the specified bit in x.

(2) Bitwise OR |

As long as one of them is 1, the result will be 1.

0|0=0; 0|1=1; 1|0=1; 1|1=1;

For example: 51|5 is 0011 0011 | 0000 0101 =0011 0111 Therefore, 51|5=55

Special usage

is often used to set 1 to certain positions of a data.

Method: Find a number that corresponds to the bit of x to be set to 1. The corresponding bit of the number is 1 and the remaining bits are zero. This number is relative to x or sets some position in x to 1.

(3) XOR ^

两个相应位为“异”(值不同),则该位结果为1,否则为0

0^0=0; 0^1=1; 1^0=1; 1^1=0;

例如:51^5 即0011 0011 ^ 0000 0101 =0011 0110 因此51^5=54

特殊用法

(1)  与1相异或,使特定位翻转

方法:找一个数,对应X要翻转的位,该数的对应为1,其余位为零,此数与X对应位异或即可。

例如:X=1010 1110,使X低四位翻转,用X^0000 1111=1010 0001即可得到。

(2)  与0相异或,保留原值

例如:X^0000 0000 =1010 1110

(3)两个变量交换值

1.借助第三个变量来实现

C=A;A=B;B=C;

2.利用加减法实现两个变量的交换

 A=A+B;B=A-B;A=A-B;

3.用位异或运算来实现,也是效率最高的

原理:一个数异或本身等于0 ;异或运算符合交换律

A=A^B;B=A^B;A=A^B

(四)取反与运算~

对一个二进制数按位取反,即将0变为1,1变0

~1=0 ;~0=1

(五)左移ef2e0777a52d953702377063955bd7b8>

将一个数的各二进制位全部右移若干位,正数左补0,负数左补1,右边丢弃。若右移时舍高位不是1(即不是负数),操作数每右移一位,相当于该数除以2。

左补0还是补1得看被移数是正还是负。

例如:

4>>2=4/2/2=1
        -14(即1111 0010)>>2 =1111 1100=-4

(七)无符号右移运算>>>

各个位向右移指定的位数,右移后左边空出的位用零来填充,移除右边的位被丢弃。

例如:-14>>>2

(即11111111 11111111 11111111 11110010)>>>2

=(00111111 11111111 11111111 11111100)=1073741820

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

上述提到的负数,他的二进制位表示和正数略有不同,所以在位运算的时候也与正数不同。

负数以其正数的补码形式表示!

以上述的-14为例,来简单阐述一下原码、反码和补码。

原 码

一个整数按照绝对值大小转化成的二进制数称为原码

例如:00000000 00000000 00000000 00001110 是14的原码。

反 码

将二进制数按位取反,所得到的新二进制数称为原二进制数的反码。

例如:将00000000 00000000 00000000 00001110 每一位取反,

得11111111 11111111 11111111 11110001

注意:这两者互为反码

补 码

反码加1称为补码

11111111 11111111 11111111 11110001 +1=
11111111 11111111 11111111 11110010

现在我们得到-14的二进制表示,现在将它左移

-14(11111111 11111111 11111111 11110010)<<2 =
11111111 11111111 11111111 11001000
=?

分析:这个二进制的首位为1,说明是补码形式,现在我们要将补码转换为原码(它的正值)

跟原码转换为补码相反,将补码转换为原码的步骤:

补码减1得到反码:(11000111)前24位为1,此处省略

反码取反得到原码(即该负数的正值)(00111000)

计算正值,正值为56

取正值的相反数,得到结果-56

结论:-146b16d268a589aedbdf68e28c86e0345c>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Java中基本数据类型有以下四种:

Int数据类型:byte(8bit,-128~127)、short(16bit)、int(32bit)、long(64bit)

float数据类型:单精度(float,32bit ) 、双精度(double,64bit)

boolean类型变量的取值有true、false(都是1bit)

char数据类型:unicode字符,16bit

对应的类类型:

Integer、Float、Boolean、Character、Double、Short、Byte、Long

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

(一)数据类型转为字节

例如:int型8143(00000000 00000000 00011111 11001111)

=>byte[] b=[-49,31,0,0]

第一个(低端)字节:8143>>0*8 & 0xff=(11001111)=207(或有符号-49)

第二个(低端)字节:8143>>1*8 &0xff=(00011111)=31

第三个(低端)字节:8143>>2*8 &0xff=00000000=0

第四个(低端)字节:8143>>3*8 &0xff=00000000=0

 

我们注意到上面的(低端)是从右往左开始的,那什么是低端呢?我们从大小端的角度来说明。

小端法(Little-Endian)

低位字节排放在内存的低地址端即该值的起始地址,高位字节排位在内存的高地址端

大端法(Big-Endian)

高位字节排放在内存的低地址端即该值的起始地址,低位字节排位在内存的高地址端

 

为什么会有大小端模式之分呢?

这是因为在计算机系统中,我们是以字节为单位的,每个地址单元都对应着一个字节,一个字节为8bit。但是在C语言中除了8bit的char之外,还有16bit的short型,32bit的long型(要看具体的编译器),另外,对于位数大于8位的处理器,例如16位或者32位的处理器,由于寄存器宽度大于一个字节,那么必然存在着一个如果将多个字节安排的问题。因此就导致了大端存储模式和小端存储模式。例如一个16bit的short型x,在内存中的地址为0x0010,x的值为0x1122,那么0x11为高字节,0x22为低字节。对于大端模式,就将0x11放在低地址中,即0x0010中,0x22放在高地址中,即0x0011中。小端模式,刚好相反。我们常用的X86结构是小端模式,而KEIL C51则为大端模式。很多的ARM,DSP都为小端模式。有些ARM处理器还可以由硬件来选择是大端模式还是小端模式。

例如:32bit的数0x12 34 56 78(十二进制)

在Big-Endian模式CPU的存放方式(假设从地址0x4000开始存放)为


内存地址

   

0x4000

   

0x4001

   

0x4002

   

0x4003

   



存放内容

   

0x78

   

0x56

   

0x34

   

0x12

   


在Little-Endian模式CPU的存放方式(假设从地址0x4000开始存放)为


内存地址

   

0x4000

   

0x4001

   

0x4002

   

0x4003

   



存放内容

   

0x12

   

0x34

   

0x56

   

0x78

   


 (二)字符串转化为字节

1.字符串->字节数组

1 String s;
2 byte[] bs=s.getBytes();

2.字节数组->字符串

1 Byte[] bs=new byte[int];
2 String s =new String(bs);或
3 String s=new String(bs,encode);//encode指编码方式,如utf-8

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

两种类型转化为字节的方法都介绍了,下面写个小例子检验一下:

public class BtyeTest {
    /*
     * int整型转为byte字节
     */
    public static byte[] intTOBtyes(int in){
        byte[] arr=new byte[4];
        for(int i=0;i<4;i++){
            arr[i]=(byte)((in>>8*i) & 0xff);
        }
        return arr;
    }
    /*
     * byte字节转为int整型
     */
    public static int bytesToInt(byte[] arr){
        int sum=0;
        for(int i=0;i<arr.length;i++){
            sum+=(int)(arr[i]&0xff)<<8*i;
        }
        return sum;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        byte[] arr=intTOBtyes(8143);
        for(byte b:arr){
            System.out.print(b+" ");
        }
        System.out.println();
        System.out.println(bytesToInt(arr));
        
        //字符串与字节数组
        String str="云开的立夏de博客园";
        byte[] barr=str.getBytes();
        
        String str2=new String(barr);
        System.out.println("字符串转为字节数组:");
        for(byte b:barr){
            System.out.print(b+" ");

        }
        System.out.println();

        System.out.println("字节数组换位字符串:"+str2);
        
         
    }

}


The above is the detailed content of Detailed explanation of binary and bit operations in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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