Binary and basic bit operations in Java

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

Binary and basic bit operations in Java

Binary is a kind of system widely used in computing. Binary data is a number represented by 0 and 12 digits. Its base is 2, the rounding rule is "every two in one", the borrow rule is "borrowing one as two", which was found by the 18th century German mathematical philosophy master Leibniz. The current computer system is basically binary systems, the data in the computer is mainly in the form of complement storage. The binary in the computer is a very small switch, with "on" to indicate 1, "off" to represent 0.

So what about the binary in Java? Let us come together to uncover the veil of mystery.

One, Java built-in conversion

The basic arithmetic for decimal to binary, and binary to decimal, does not unfold here.

Several methods have been built into Java to help us with various conversions. As shown (in integer shaping as an example, other types are identical):

1, decimal conversion to other binary:

1 binary: integer.tohexstring (int  i); 2 octal: integer.tooctalstring (int  i); 3 16 binary: integer.tobinarystring (int i);

2, other conversions into decimal:

1 binary: integer.valueof ("0101", 2). toString; 2 octal: integer.valueof ("376", 8). toString; 3 16 binary: integer.valueof ("FFFF", +). toString;

3, using the parseint () method and the ValueOf () method in the integer class, you can convert the other binary to 10 binary.

The difference is that the return value of the parseint () method is of type int, and the valueof () return value is an integer object.

Second, the basic bit operation

Binary can be as subtraction as decimal, but it also has a simpler way of doing it--bit arithmetic. For example, the size of the int type in the computer is 32bit, can be represented by a 32-bit binary number, so we can use bit operation to calculate the value of int type, of course, you can also use the usual method to calculate some data, here I mainly introduce the method of bit operation. We will find that the bitwise operation has the incomparable power of the ordinary arithmetic method. more bit computing applications please transfer to my next post, "Magic bit operation"

First, look at the basic operator of the bitwise operation:

Advantages:

    • In certain cases, the calculation is convenient, the speed is fast, the support surface is wide
    • If you use arithmetic, the speed is slow, the logic is complex
    • Bit operation is not limited to a language, it is the basic computing method of computer

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

(a) Bitwise AND &

Two bits are all 1, and 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 so 51&5=1.

Special usage

(1) clear Zero. If you want to clear a unit to zero, even if all of its bits is 0, as long as it is zero with one of you, the result is zero.

(2) take a number to locate the middle finger.

For example: Set x=10101110, take x low four bits, with x&0000 1111=0000 1110 can be obtained.

Method: Find a number, corresponding to the x to take the bit, the corresponding bit of the number is 1, the rest of the bits are zero, this number and X for "and operations" can be obtained by means of X-position.

(b) Bitwise OR |

As long as one is 1, the result is 1.

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

Example: 51|5 0011 0011 | 0000 0101 = 0011 0111 so 51|5=55

Special usage

Often used for some location of a data 1.

Method: Find a number, corresponding to the x to set 1 bits, the corresponding bit of the number is 1, the remaining bits are zero. This number is in X-phase or can make some position in X 1.

(c) Xor ^

Two the corresponding bit is "XOR" (the value is different), then the bit result is 1, otherwise 0

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

For example: 51^5 is 0011 0011 ^ 0000 0101 = 0011 0110 so 51^5=54

Special usage

(1) differ from 1 or, make certain bits flip

Method: Find a number, corresponding to the X to flip the bit, the number corresponds to 1, the remaining bits are zero, this number and x corresponding bit XOR.

For example: x=1010 1110, so that X low four-bit flip, with x^0000 1111=1010 0001 can be obtained.

(2) differ from 0 or, retain the original value

Example: x^0000 0000 = 1010 1110

(3) two variable exchange values

1. Use the third variable to achieve

C=a; A=b; B=c;

2. Using addition and subtraction to realize the exchange of two variables

A=a+b; B=a-b; A=a-b;

3. It is also the most efficient to achieve by using the bitwise XOR OR operation.

Principle: A number XOR or itself equals 0; an XOR operation conforms to the commutative law.

A=a^b; B=a^b; A=a^b

(d) Negation and computation ~

Reverse the bitwise of a binary number, turn 0 to 1, 1 to 0

~1=0; ~0=1

(v) Shift left <<

Shift all bits of an operand to the left of a number of bits (left bits discarded, 0 on the right)

Example: 2<<1 =4 10<<1=100

If the left-hand side does not contain 1, then each left-shift is equal to the number multiplied by 2.

For example:

One (1011) <<2= 0010 1100=22

11 (00000000 00000000 00000000 1011) Plastic 32bit

(vi) Right SHIFT >>

All bits of a number are shifted to the right by a number of digits, positive left 0, negative left 1, and right discard. If the right shift is not 1 (that is, it is not a negative number), the operand shifts one bit to the right, equal to the number divided by 2.

The left complement 0 or 1 depends on whether the number of shifts is positive or negative.

Example: 4>>2=4/2/2=1

-14 (i.e. 1111 0010) >>2 = 1111 1100=-4

(vii) Unsigned right SHIFT operation >>>

The bits are shifted to the right by the specified number of bits, and the left-vacated bits are filled with zero after the right shift , and the bits to the right are discarded.

Example: -14>>>2

(i.e. 11111111 11111111 11111111 111100) >>>2

= (111111 11111111 11111111 11111100) =1073741820

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

The negative number mentioned above, his bits expression and positive number slightly different, so the time of the bit is also different from positive.

negative numbers are expressed in the complement form of their positive numbers !

Take the above-14 as an example, to briefly explain the original code, anti-code and complement.

Original code

A binary number converted to an integer in absolute size is called the original code.

For example: 00000000 00000000 00000000 00001110 is the original code of 14.

Anti-code

The binary number is reversed by a bit, and the resulting new binary number is called the inverse of the original binary number.

For example: 00000000 00000000 00000000 00001110 Every bit of the reverse,

Get 11111111 11111111 11111111 11110001

Note: The two are anti-code

Complement

Anti-code plus 1 is called complement

11111111 11111111 11111111 11110001 +1=

11111111 11111111 11111111 11110010

Now we get a binary representation of-14, now move it to the left

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

11111111 11111111 11111111 110010

=

Analysis: The first of the binary is 1, which shows the complement form, now we want to convert the complement to the original code (its positive value)

Instead of converting the original code to complement, the steps to convert the complement to the original code:

    1. Complement minus 1 Gets the inverse code: (11000111) The first 24 bits are 1, omitted here
    2. Inverse code to get the original code (that is, the positive value of the negative number) (00111000)
    3. Evaluates to a positive value of 56
    4. Take the opposite number of positive values and get the result-56

Conclusion: -14<<2 = 56

Third, Java in the binary operation

Is there more binary in Java?

Usually in the development of "conversion" and "bit operation" with a few, Java processing is high-level.

In the cross-platform used more, such as: file read and write, data communication.

Look at a scene:

If both the client and the server are programs written in the Java language, then when the client sends the object data, we can serialize the data to be sent serializable, and the server will be able to deserialize the serialized data and read the object data.

With the increase of client access, we do not consider the performance of the server, in fact, a feasible solution is to change the server's Java language to C language.

C language as the underlying language, the speed is faster than the Java language, and at this time if the client pass or serialized data, then the server side of the C language will not be resolved, how to do? We can turn the data into binary (0,1) so that the server can parse those languages.

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

There are four basic data types in Java:

    1. int data type: Byte (8bit,-128~127), short (16bit), int (32bit), Long (64bit)
    2. Float data type: Single precision (float,32bit), double precision (double,64bit)
    3. Boolean variable evaluates to True, False (both 1bit)
    4. Char data type: Unicode character, 16bit

The corresponding class type:

Integer, Float, Boolean, Character, Double, short, Byte, Long

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

(i) Data type to byte

Example: int type 8143 (00000000 00000000 00011111 11001111)

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

First (low-end) Byte: 8143>>0*8 & 0xff= (11001111) =207 (or signed-49)

Second (low-end) byte: 8143>>1*8 &0xff= (00011111) =31

Third (low-end) byte: 8143>>2*8 &0xff=00000000=0

Fourth (low-end) byte: 8143>>3*8 &0xff=00000000=0

We notice that the above (low end) starts from right to left, what is the low end? We explain from the angle of the size side.

Small End Method (Little-endian)

low bit byte emissions at low address end of memory that is the starting address of this value, high bit byte rank at High address end of memory

Big-endian method (Big-endian)

high bit byte emissions at low address end of memory that is the starting address of this value, low bit byte rank at High address end of memory

Why do you have the size and end mode of the points?

This is because in the computer system, we are in bytes, each address unit corresponds to a byte, one byte is 8bit. But in the C language In addition to 8bit of Char, there are 16bit short type, 32bit long (to see the specific compiler), in addition, for the number of bits greater than 8 bits of the processor, such as 16-bit or 32-bit processor, Because the register width is greater than one byte, there must be an issue where multiple bytes are scheduled. The result is a big-endian storage mode and a small-end storage mode. For example, a 16bit short x, where the value of address 0x0010,x in memory is 0x1122, then 0x11 is a high byte and 0x22 is a low byte. For big-endian mode, put 0x11 in the low address, that is, 0x0010, 0x22 placed in the high address, that is, 0x0011. Small-end mode, just the opposite. The X86 structure we commonly use is the small-end mode, while the Keil C51 is the big-endian mode. Many of the arm,dsp are in the small-end mode. Some arm processors can also be hardware to choose between big-endian or small-end mode.

Example: Number of 32bit 0x12 34 56 78 (12 binary)

The way the CPU is stored in the Big-endian mode (assuming that the store starts from address 0x4000) is

Memory address

0x4000

0x4001

0x4002

0x4003

Store content

0x78

0x56

0x34

0x12

The way the CPU is stored in the Little-endian mode (assuming that the store starts from address 0x4000) is

Memory address

0x4000

0x4001

0x4002

0x4003

Store content

0x12

0x34

0x56

0x78

Two string translates to bytes

1. Byte array, string

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

2. Byte array-string

1 byte[] bs=newByte[int]; 2 string s =new  string (BS), or 3 string s=new string (Bs,encode); // encode refers to the encoding method, such as Utf-8

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

Two types of conversion to byte methods are introduced, the following is a small example to examine:

1  Public classBtyetest {2     /*3 * int integer to byte byte4      */5      Public Static byte[] Inttobtyes (intIn ) {6         byte[] arr=New byte[4];7          for(inti=0;i<4;i++){8Arr[i]= (byte) ((in>>8*i) & 0xFF);9         }Ten         returnarr; One     } A     /* - * byte byte to int integer -      */ the      Public Static intBytestoint (byte[] arr) { -         intSum=0; -          for(inti=0;i<arr.length;i++){ -sum+= (int) (ARR[I]&AMP;0XFF) <<8*i; +         } -         returnsum; +     } A      Public Static voidMain (string[] args) { at         //TODO auto-generated Method Stub -         byte[] Arr=inttobtyes (8143); -          for(byteB:arr) { -System.out.print (b + ""); -         } - System.out.println (); in System.out.println (Bytestoint (arr)); -          to         //string and byte array +String str= "cloud-opened Li Xia Zhong de blog Park"; -         byte[] barr=str.getbytes (); the          *String str2=NewString (Barr); $System.out.println ("string converted to byte array:");Panax Notoginseng          for(byteB:barr) { -System.out.print (b + ""); the  +         } A System.out.println (); the  +System.out.println ("byte array transposition string:" +str2); -          $           $     } -  -}

Operation Result:

Concluding remarks: Recently lazy, did not study hard, for several days did not write the text, hey, also please a lot of supervision!

Binary and basic bit operations in Java

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.