Java implementation of computer composition principle

Posted by Easter Bunny on Mon, 08 Jun 2020 05:19:43 +0200

1 purpose of course design
This course is designed to deepen students' basic knowledge of the course of computer composition principle, further understand some algorithms of computer composition principle, and carry out specific implementation, so as to improve the comprehensive application ability of analyzing and solving problems.
2 Contents and requirements of curriculum design
1. Title:
Algorithm realization of computer composition principle (5)
2. Function:
It can realize the true value reduction of machine number (fixed-point integer), the single sign bit complement addition and subtraction of fixed-point integer, the original one bit multiplication of fixed-point integer and the addition and subtraction of floating-point number.
3. Detailed design of functional modules
3.1 main window design

Figure 3-1 main interface figure 3-2 password success

Design of system entry (main) window: the menu can be activated only after the password is entered correctly. In case of wrong password input, the prompt of re entering password shall be given. The front-end language used in the course design is html,css, and jQuery. The logic code of the back-end is written in java. The course design is based on the idea of separating the front-end and the back-end. The front-end is only responsible for the display of the interface, and the back-end is only responsible for the logic part.
3.2 main functions
1.login.jsp
The jsp file is the front-end interface code of the whole program.
2.Calculate.css
The css file is responsible for the style of the front-end interface.
Three Calculate.js And jquery-1.10.1.js
These javascript files are responsible for the behavior of the front-end interface and the interaction with the back-end.
4.trueNumber.java
The java class is responsible for receiving requests and data from the front end and responding the true value of the number of machines to the front end.
5.dzdfplus.java
The java class is responsible for receiving the request and data from the front end, and responding the single sign bit complement addition and subtraction operation result of fixed-point integer to the front end.
6.dzymcf.java
The java class is responsible for receiving the request and data from the front end, and responding the original code multiplication result of fixed-point integer to the front end.
7.fdplusminus.java
The java class is responsible for receiving requests and data from the front end, and responding the addition and subtraction results of floating-point numbers to the front end.
3.2.1 fixed point integer true value restoration
Click the machine number true value restore button in the main interface, as shown in Figure 3-3

Figure 3-3 fixed point integer true value restoration
When you press the enter button in the form above, set the input focus to the top text box. After inputting a number of machines (such as 10011), press any of the "original code", "inverse code", "complement code" or "shift code" buttons to display the results of corresponding operations in the second text box. Selecting the back button will close this form and return to the password login interface.
Fixed point representation: it is agreed that the decimal position of all data in the machine is fixed. Since the Convention is in a fixed position, the decimal point is no longer represented by a ".".
Generally speaking, the data represented by writing is called true value. In order to represent symbol bit in computer, symbol bit and number bit are usually coded together to represent corresponding number, forming various data storage and representation methods. These codes are called machine code. The commonly used machine codes are source code, inverse code, complement code and shift code.
Algorithm idea:
(1) Original code: the numerical part of the original code is the absolute value of the number, the highest bit represents the sign bit, the highest bit is 0 is a positive number, and the highest bit is 1 is a negative number. So we only need to judge the highest symbol, and the latter one doesn't need to be changed.
(2) Inverse code: the inverse code of a positive number is equal to the original code, and the inverse code of a negative number is equal to the binary number 0 becomes 1 and 1 becomes 0 except for the sign bit. The negative value part is stored in the array first, then traverses the array and reverses it, and then converts the symbol into a string response to the front end.
Positive number: [x] negative = [x] original = x; negative number: the sign bit is unchanged, the rest is reversed
(3) Complement: the complement of a positive number is equal to the original code, and the complement of a negative number is equal to the inverse code plus 1. First, the inverse code of the negative number is stored in the array, then the binary addition is realized by the array, and finally the array is converted into a string response to the front end.
Positive: [x] complement = [x] original; negative: [x] complement = [x] inverse + 1
(4) Shift code: it is a complement code of reverse sign bit, generally used as the order code of floating-point number. The purpose of introducing it is to ensure that the machine code of floating-point number is all 0.
3.2.2 single sign bit complement addition and subtraction of fixed-point integer
In the implementation of single sign digit complement addition and subtraction method of fixed-point integer, the corresponding menu item is selected in the main window, and then the corresponding window is entered for specific operation. During operation, first select the "input" button to input the data involved in the operation, and then select the operation button. As shown in Figure 3-4

Figure 3-4 single sign bit complement addition and subtraction of fixed-point integer

The implementation of single sign digit complement addition and subtraction method of fixed-point integer, input button, delete all data, move cursor to the first input window, start input, pay attention to the input of true value, when the implementation of fixed-point integer addition and subtraction method, first judge the sign bit, then convert it into its complement form and store it in array, and use array to realize the addition of complement,
In order to realize subtraction, it is necessary to take the negative subtraction and all the symbols in it as the inverse plus 1, then use array to realize addition, and convert subtraction into addition. When using array to realize addition, it is necessary to record the carry Cf of the highest sign bit and the carry C0 of the most significant bit to determine whether the result overflows. Finally, the complement result is converted to true value output.
Algorithm idea:
(1) All the numbers in the operation are represented by complement.
(2) The symbols of data participate in the operation just like data. Store values in an array operation.
(3) In the process of subtraction, negative subtraction is complemented, and summation is used instead of subtraction.
(4) The operation result is complement. Finally, the complement result is converted to true value output.
(5) The carry of the highest sign bit is Cf, and the significant bit of the highest value is C0
Overflow: in the fixed-point number machine, the size of the number exceeds the range that the fixed-point number can represent, which is called overflow.
(1) In the fixed-point decimal machine, the range of the number is - 1 < x < 1. If there is more than 1 or less than - 1 in the operation process.
(2) In the fixed-point integer machine (8-bit), the range of the number is - 128 < x < 127. If there is more than 127 or less than - 128 in the operation process.
Single sign bit method: when the most significant bit generates carry and the sign bit has no carry, a positive overflow is generated; when the most significant bit has no carry and the sign bit has carry, a negative overflow is generated. Therefore, the logical expression of single sign bit overflow is V=Cf exclusive or C0. In the fixed-point machine, when the operation result overflows, it indicates an error. The machine automatically detects the overflow through the logic circuit and carries out the interrupt processing.
① CF = 0 & & C0 = 1, result positive overflow
② CF = 1 & & C0 = 0, result negative overflow
③ CF = 0 & & C0 = 0| CF = 1 & & C0 = 1, result does not overflow

3.2.3 original code multiplication of fixed-point integer

The implementation of fixed-point integer original code multiplication is to enter the corresponding window after selecting the corresponding menu item in the main window and then carry out specific operations. During operation, first select the "input" button to input the data involved in the operation, and then select the operation button. As shown in Figure 3-5

Figure 3-5 original code multiplication of fixed-point integer

Machine algorithm: one method in the machine is to use the method of "addition shift" for many times. It is called serial multiplier. Its hardware structure is simple, but its speed is slow. At present, the pipeline array multiplier, called parallel multiplier, is widely used. The key of parallel multiplier is to generate m n bit product quickly, and to add the bit product to generate m+n colu mn sum.
Algorithm idea:
Analog machine algorithm: serial multiplier
(1) First, enter the true value of the multiplicator and the multiplier to determine the sign bit. If the sign bit is the same, the result is positive. If the different results are negative, store the original code into two arrays respectively.
(2) Declare another partial integrand group and initialize it to 0.
(3) Then start the cycle from the last bit of the multiplier array to the end of the first bit. If the last bit of the current multiplier is 1, then add the multiplier to the partial product, then move the partial product and the multiplier array to the right one bit at the same time, the first bit on the left of the partial product is filled with 0, the first bit on the left of the multiplier is filled with the last bit of the partial product, if the current multiplier is the most If the latter bit is 0, then the partial product and multiplier move right again until the first bit of multiplier ends.
(4) Finally, the multiplier array and the multiplicator array are spliced into a string, and the symbol bit is added before the result to respond the result to the front end.

3.2.4 addition and subtraction of floating-point numbers

In the implementation of single sign digit complement addition and subtraction method of fixed-point integer, the corresponding menu item is selected in the main window, and then the corresponding window is entered for specific operation. During operation, first select the "input" button to input the data involved in the operation, and then select the operation button. As shown in Figure 3-6

Figure 3-6 addition and subtraction of floating point number

Data input is divided into order code and mantissa. The two order codes and the corresponding deformation complement of the mantissa are represented. The size of the price code is compared and the order is aligned, i.e. the small order is aligned with the large order. If the order overflows, a reminder will be sent. After unifying the order codes, the mantissa sum is calculated by normalization, the mantissa is rounded, and the end of the mantissa is judged. The rough rounding is realized by Replace statement In processing. Finally, the deformation complement is restored.
Algorithm idea:
The addition and subtraction of floating-point numbers can be divided into six steps:
(1) 0 operand check
The process of floating-point addition and subtraction is more complex than that of fixed-point operation. If one of the two operands X or Y is judged to be 0, then the result of the operation can be obtained without the need for a series of subsequent operations to save the operation time. The 0 operand check step is used to complete this function. The data involved in the addition operation are all non-zero, and go to the next step.
(2) Compare order code size and complete order matching
In order to facilitate intuitive understanding, it is assumed that both numbers are represented by complement, the order code adopts double sign bits, and the mantissa adopts single sign bits. To add or subtract two floating-point numbers, first of all, it is necessary to see whether the order codes of the two numbers are the same. If the order codes of the two numbers are different, it means that the decimal point position is not aligned. At this time, the order codes of the two numbers must be the same. This process is called order matching. In order operation, the mantissa is shifted to the right and the order code is increased accordingly after the mantissa is shifted to the right. Therefore, in order operation, the small order is always aligned with the large order.
(3) Add and subtract mantissa
After the completion of the order, you can sum the mantissa. No matter add operation or subtract operation, all operations are carried out according to add (subtraction is done by converting complement subtraction to complement addition), and the method is exactly the same as fixed-point addition and subtraction operation.
(4) Results normalization
① When using double sign bits to represent mantissa, if the two sign bits are 01 or 10, move the result mantissa one bit to the right, and add 1 to the order code (called "right gauge").
② If the highest value bit of the mantissa is the same as the symbol bit, move the mantissa to the left, and decrease the order code by 1 until the highest value bit is opposite to the symbol bit (called "left gauge").
(5) Rounding operation
In order to normalize the order to the right, the mantissa is shifted to the right, so that the lower part of the mantissa that is shifted to the right will be lost, resulting in some errors, so rounding is necessary.
There are two simple rounding methods: one is "0 rounding", that is, if the highest digit of the lost digit is 0 when it is shifted to the right, it will be rounded off, and if it is 1, it will add 1 to the last digit of the mantissa. The other is "constant 1", that is, as long as the digit is removed, it will be set at the end of the mantissa.
(6) Judge whether the result overflows
The order code is 00 011, and the symbol bit of the order code is 00. According to the method of double symbol detection overflow of complement, the order code does not overflow.
4 design summary
Through this course design of computer composition principle, I not only reviewed the knowledge of computer composition principle I learned last semester, but also consolidated the knowledge of front-end, reviewed html, css, jQurey and other languages, and realized the java language for back-end, and improved my hands-on ability. I feel that only by constantly tapping the code can I constantly skillfully use it, and only by tapping it can I really do it To master it, we can't just stay in theory and talk about it on paper. Only through continuous practice can we have a deeper understanding. On the one hand, we can feel the sense of achievement knocked out, on the other hand, we can realize our own shortcomings and shortcomings, so that we can have more motivation to continue. Finally, on this basis, we can summarize and improve our understanding of knowledge.
After this course design, I think it will have many benefits and influences for my future computer related study, and lay a solid foundation for my future study and life. In the future, we will not be unable to deal with these problems. Through this design, I also understand the way out. If I don't understand what I don't understand, I need to consult or inquire online in time. As long as I study carefully, think with my brain, and practice with hands, I have no knowledge that I don't understand, and I have gained a lot.

reference
[1] Bai Zhongying. Principles of computer composition (Fifth Edition) [M]. Beijing: Science Press, 2010
[2] Geng Xiangyi, Zhang Yueping. Java 2 practical course (Fifth Edition) [M]. Beijing: Tsinghua University Press, 2017

Source code list

/Calculate/src/servlet/trueNumber.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/trueNumber")
public class trueNumber extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String result=null;
String number = req.getParameter("number");
String name = req.getParameter("btnname");
if (name.equals("yuanma")) {
result = yuanmaResult(number);
}
if (name.equals("buma")) {
result = bumaResult(number);
}
if (name.equals("fama")) {
result = famaResult(number);
}
if (name.equals("yima")) {
result = yimaResult(number);
}
resp.getWriter().write(result);
}

private String yimaResult(String number) {
	String result;
	if(number.charAt(0)=='0') {
		result = "-";
		result = result + number.substring(1, number.length());
	}
	else {
		result = "+";
		for(int i = 1;i<number.length();i++) {
			if(number.charAt(i)=='0')
				result = result + "1";
			else {
				result = result + "0";
			}
		}
		//System.out.println(result.length());//5
		int arr[] = new int[result.length()-1];
		//System.out.println(arr.length);//4
		for(int j = 1;j<result.length();j++)
			arr[j-1] = (result.charAt(j))-48;
		int lastindex = arr.length-1;
		//System.out.println(arr[lastindex]);//0
		int flag=0;
		if(arr[lastindex]==0) {
			arr[lastindex]=1;
			flag=0;
		}
		else {
				arr[lastindex]=0;
				flag=1;
			}
		for(int k=(lastindex-1);k>=0;k--) {
			arr[k]=arr[k]+flag;
			if(arr[k]==0||arr[k]==1) flag=0;
			if(arr[k]==2) {
				arr[k]=0;
				flag=1;
			}
		}
		result = "+";
		StringBuffer sb = new StringBuffer();
		for(int m=0;m<arr.length;m++)
			sb.append(arr[m]);
		result = result + sb.toString();
		//System.out.println(result);
	}
	return result;
}
private String famaResult(String number) {
	String result;
	if(number.charAt(0)=='0') {
		result = "+";
		result = result + number.substring(1, number.length());
	}
	else {
		result = "-";
		for(int i = 1;i<number.length();i++) {
			if(number.charAt(i)=='0')
				result = result + "1";
			else {
				result = result + "0";
			}
		}
	}
	return result;
}

private String bumaResult(String number) {
	String result;
	if(number.charAt(0)=='0') {
		result = "+";
		result = result + number.substring(1, number.length());
	}
	else {
		result = "-";
		for(int i = 1;i<number.length();i++) {
			if(number.charAt(i)=='0')
				result = result + "1";
			else {
				result = result + "0";
			}
		}
		//System.out.println(result.length());//5
		int arr[] = new int[result.length()-1];
	//System.out.println(arr.length);//4
		for(int j = 1;j<result.length();j++)
			arr[j-1] = (result.charAt(j))-48;
		int lastindex = arr.length-1;
		//System.out.println(arr[lastindex]);//0
		int flag=0;
		if(arr[lastindex]==0) {
			arr[lastindex]=1;
			flag=0;
		}
		else {
				arr[lastindex]=0;
				flag=1;
			}
		for(int k=(lastindex-1);k>=0;k--) {
			arr[k]=arr[k]+flag;
			if(arr[k]==0||arr[k]==1) flag=0;
			if(arr[k]==2) {
				arr[k]=0;
				flag=1;
			}
		}
		result = "-";
		StringBuffer sb = new StringBuffer();
		for(int m=0;m<arr.length;m++)
			sb.append(arr[m]);
		result = result + sb.toString();
		//System.out.println(result);
	}
	return result;
}

private String  yuanmaResult(String number) {
	String result = null;
	if (number.charAt(0) == '0') {
		result = "+";
			} else {
		result = "-";

} }
result = result + number.substring(1, number.length());
//System.out.println(result);
return result;
}
}
/Calculate/src/servlet/dzdfplus.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/dzdfplus")
public class dzdfplus extends HttpServlet {
private static final long serialVersionUID = 1L;
//Carry to store symbol bit and most significant bit
int cf=0,c0=0;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Format response data
resp.setContentType("text/html;charset=utf-8");
//Store result data
String result=null;
//Get relevant data
String number1 = req.getParameter("number1");
String number2 = req.getParameter("number2");
String name = req.getParameter("btnname");

	//Distinguish the plus and minus types of request processing
	if(name.equals("plus")) {
		result = plusResult(number1,number2);
	}else {
		result = minusResult(number1,number2);
	}
	if(cf==0&&c0==1) {
		result=result+"(Result positive overflow)";
	}
	if(cf==1&&c0==0) {
		result=result+"(Result negative overflow)";
	}
	//Response processing results to the front end
	resp.getWriter().write(result);
	
}

/**
 * @param number1  Signed true string
 * @param number2  Signed true string
 * @return  Single sign complement subtraction result
 */
private String plusResult(String number1, String number2) {
		String result = null;
		int[] number1arr= bumaResult(number1);
		int[] number2arr= bumaResult(number2);
		int[] resultarr=binPlus(number1arr,number2arr);
		if(resultarr[0]==0) result="+";
		if(resultarr[0]==1) result="-";
		StringBuffer sb = new StringBuffer();		
		for(int m=1;m<resultarr.length;m++)
			sb.append(resultarr[m]);
		result = result + sb.toString();
		System.out.println(result);
		return result;
	}

/**
 * @param number1: Signed true string
 * @param number2    Signed true string
 * @return Single sign complement subtraction result
 */
private String minusResult(String number1, String number2) {
	String result= null;
	int[] number1arr= bumaResult(number1);
	int[] number2arr= bumaResult(number2);
	for(int i=0;i<number2arr.length;i++)
	{
		if(number2arr[i]==0) number2arr[i]=1;
		else number2arr[i]=0;
	}
	int lastindex = number2arr.length-1;
	//System.out.println(arr[lastindex]);//0
	int flag=0;
	if(number2arr[lastindex]==0){
		number2arr[lastindex]=1;
		flag=0;
	}
	else {
		number2arr[lastindex]=0;
			flag=1;
		}
	for(int k=(lastindex-1);k>=0;k--) {
		number2arr[k]=number2arr[k]+flag;
		if(number2arr[k]==0||number2arr[k]==1) flag=0;
		if(number2arr[k]==2) {
			number2arr[k]=0;
			flag=1;
		}
	}
	int[] resultarr=binPlus(number1arr,number2arr);
	if(resultarr[0]==0) result="+";
	if(resultarr[0]==1) result="-";
	StringBuffer sb = new StringBuffer();		
	for(int m=1;m<resultarr.length;m++)
		sb.append(resultarr[m]);
	result = result + sb.toString();
	System.out.println(result);
	return result;	
}

/**
 * @param number Enter a string of true values with signed bits
 * @return  Integer array with complement as result
 */
private int[] bumaResult(String number) {
	String result;
	int a[];
	if(number.charAt(0)=='+') {
		result = "0";
		result = result + number.substring(1, number.length());
		int arr[] = new int[result.length()];
		for(int j = 0;j<result.length();j++)
			arr[j] = (result.charAt(j))-48;
		a=arr;
	}
	else {
		result = "1";
		for(int i = 1;i<number.length();i++) {
			if(number.charAt(i)=='0')
				result = result + "1";
			else {
				result = result + "0";
			}
		}
		//System.out.println(result.length());//5
		int arr[] = new int[result.length()];
		//System.out.println(arr.length);//4
		for(int j = 0;j<result.length();j++)
			arr[j] = (result.charAt(j))-48;
		int lastindex = arr.length-1;
		//System.out.println(arr[lastindex]);//0
		int flag=0;
		if(arr[lastindex]==0) {
			arr[lastindex]=1;
			flag=0;
		}
		else {
				arr[lastindex]=0;
				flag=1;
			}
		for(int k=(lastindex-1);k>=0;k--) {
			arr[k]=arr[k]+flag;
			if(arr[k]==0||arr[k]==1) flag=0;
			if(arr[k]==2) {
				arr[k]=0;
				flag=1;
			}
		}
		a=arr;
	}
	return a;
}

/**
 * @param number1arr  Binary integer array
 * @param number2arr  Binary integer array
 * @return Returns an integer array of binary sums
 */
public int[] binPlus(int[] number1arr, int[] number2arr) {
	int[] result=new int[number1arr.length];
	int flag=0;
	for (int i = (number1arr.length-1); i >=0 ; i--) {
		result[i]=number1arr[i]+number2arr[i]+flag;
		if(result[i]==0||result[i]==1) {
			flag=0;
		}
		if(result[i]==2) {
			result[i]=0;
			flag=1;
		}
		if(result[i]==3) {
			result[i]=1;
			flag=1;
		}
		if(i==1) c0=flag;
	}
	cf=flag;
	return result;
}

}
/Calculate/src/servlet/dzymcf.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/dzymcf")
public class dzymcf extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	resp.setContentType("text/html;charset=utf-8");
	//Get relevant data
	String number1 = req.getParameter("number3");
	// System.out.println(number1);
	String number2 = req.getParameter("number4");
	// System.out.println(number2);
	//Storage results
	String result;
	int length1 = number1.length();
	int length2 = number2.length();
	if (length1 != length2) {
		result = "error";
	} else {
		//Partial deposit
		int a[] = new int[length1 - 1];
		//Deposit multiplier
		int b[] = new int[length1 - 1];
		//Deposit quilt multiplier
		int a1[] = new int[length1 - 1];
		//Symbol processing
		if ((number1.charAt(0)) == (number2.charAt(0)))
			result = "+";
		else
			result = "-";
		//Convert string to integer array
		for (int i = 1; i < length1; i++) {
			a1[i - 1] = number1.charAt(i) - 48;
		}
		for (int j = 1; j < length1; j++) {
			b[j - 1] = number2.charAt(j) - 48;
		}
		//Initialization partial product
		for (int j = 0; j < b.length; j++) {
			a[j] = 0;
		}
		//Core code
		for (int i = a.length - 1; i >= 0; i--) {
			if (b[a.length - 1] == 0) {
				yiwei(a, b);
			} else if (b[a.length - 1] == 1) {
				a = binPlus(a, a1);
				yiwei(a, b);
			}
		}
		
		//Convert array to string
		StringBuffer sb = new StringBuffer();
		for (int m = 0; m < a.length; m++)
			sb.append(a[m]);
		for (int m = 0; m < b.length; m++)
			sb.append(b[m]);
		result = result + sb.toString();
	}
	resp.getWriter().write(result);
}

//displacement
private void yiwei(int a[], int b[]) {
	int alast = a[a.length - 1];
	for (int j = a.length - 1; j >= 1; j--) {
		a[j] = a[j - 1];
	}
	a[0] = 0;
	for (int j = a.length - 1; j >= 1; j--) {
		b[j] = b[j - 1];
	}
	b[0] = alast;
}

/**
 * @param number1arr  Binary integer array
 * @param number2arr  Binary integer array
 * @return Returns an integer array of binary sums
 */
//Add two arrays of 0, 1
private int[] binPlus(int[] number1arr, int[] number2arr) {
	int[] result = new int[number1arr.length];
	int flag = 0;
	for (int i = (number1arr.length - 1); i >= 

0; i–) {
result[i] = number1arr[i] + number2arr[i] + flag;
if (result[i] == 0 || result[i] == 1) {
flag = 0;
}
if (result[i] == 2) {
result[i] = 0;
flag = 1;
}
if (result[i] == 3) {
result[i] = 1;
flag = 1;
}
}
return result;
}
}
/Calculate/src/servlet/fdplusminus .java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/fdplusminus")
public class fdplusminus extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
//Get relevant data
String jiema1= req.getParameter("jiema1");
String weishu1 = req.getParameter("weishu1");
String jiema2 = req.getParameter("jiema2");
String weishu2 = req.getParameter("weishu2");
String btnname = req.getParameter("btnname");
//String holding the result
String aresultweishu = null;
String aresultjiema =null;
//An array of addends and addends
int ajiema[]=new int[jiema1.length()+1];
int aweishu[]=new int[weishu1.length()+1];
int bjiema[] = new int[jiema2.length()+1];
int bweishu[] = new int[weishu2.length()+1];
//Array of results
int resultweishu[] = new int[weishu2.length()+1];
int resultjiema[] = new int[jiema1.length()+1];
//Replace the true value of the rank string with an integer array
ajiema = bumaResult(jiema1);
//Remove "0." from mantissa
String weishu1bumaString = weishu1.replaceFirst("0.","");
//Replace the mantissa string truth value with an integer array
aweishu = bumaResult(weishu1bumaString);
bjiema = bumaResult(jiema2);
String weishu2bumaString = weishu2.replaceFirst("0.","");
bweishu = bumaResult(weishu2bumaString);

		//Antithetic order
		String chazhi = minusResult(jiema1,jiema2);	
		String chazhibumaString = buma1Result(chazhi);
		int yiweisum = Integer.parseInt(chazhibumaString, 2);
		
		//displacement
		int a[] = new int[(-yiweisum)];
		if(yiweisum<0) {
			resultjiema = bjiema;
			int lastindex = aweishu.length+yiweisum;
			for(int j=0;j<(-yiweisum);j++)
			{
				a[j]=aweishu[lastindex];
				lastindex = lastindex + 1;
			}
			aweishu = rightMove(aweishu,-yiweisum);
		}
		else {
			resultjiema = ajiema;
			//Save the shifted number to the a array
			int lastindex = bweishu.length+yiweisum;
			for(int j=0;j<(-yiweisum);j++)
			{
				a[j]=bweishu[lastindex];
				lastindex = lastindex + 1;
			}
			bweishu = rightMove(bweishu,yiweisum);
		}
		
		//System.out.println(a[0]);
		
		//Mantissa addition
		if(btnname.equals("plus")) {
			resultweishu = binPlus(aweishu, bweishu);
		}
		else if(btnname.equals("minus")) {
			for(int i=0;i<bweishu.length;i++) {
				if(bweishu[i]==0) bweishu[i]=1;
				else {
					bweishu[i] = 0;
				}
			}
			int temp1[] = new int[bweishu.length];
			for(int g = 0;g<temp1.length;g++) {
				if(g==temp1.length-1) temp1[g]=1;
				else {
					temp1[g]=0;
				}
			}
			bweishu=binPlus(bweishu,temp1);
			resultweishu = binPlus(aweishu, bweishu);
		}
	
		//Normalization of results
		if((resultweishu[0]+resultweishu[1])==1) {
			//Mantissa shift right 1 bit
			for(int i = resultweishu.length-1;i>=1;i--) {
				a[i]=a[i-1];
				}
			//Order code plus 1
			StringBuffer sb = new StringBuffer();
			for(int m=0;m<resultjiema.length;m++)
			{
				sb.append(resultjiema[m]);
				System.out.println(resultjiema[m]);
			}
			int resultjiema1=Integer.parseInt(sb.toString(),2);
			resultjiema1=resultjiema1+1;
			aresultjiema = Integer.toBinaryString(resultjiema1);
		}
		else {
			//Mantissa shift left j bit
			int b=0;
			for(int j=0;j<resultweishu.length;j++) {
				if((resultweishu[0]==0&&resultweishu[1]==0&&resultweishu[2]==1)||(resultweishu[0]==1&&resultweishu[1]==1&&resultweishu[2]==0))
					{
						if((j-1)<a.length&&a[j]==1) {
							int[] temp = new int[resultweishu.length];
							for(int k = 0;k<temp.length;k++) {
								if(k==temp.length-1) temp[k]=1;
								else temp[k]=0;
							}
						 resultweishu=binPlus(resultweishu, temp);
						}
						b=j;
						break;
					}
					for(int i = 0;i<resultweishu.length-1;i++) {
						resultweishu[i]=resultweishu[i+1];
				if((i==resultweishu.length-2)&&j<a.length){
						resultweishu[i+1]=a[j];
				   }
				if(j>=a.length) {
					resultweishu[i+1]=0;
				}
				}
			}
			//Order code minus b
			StringBuffer sb = new StringBuffer();
			StringBuffer sb1 = new StringBuffer();
			for(int m=0;m<resultjiema.length;m++)
				sb.append(resultjiema[m]);
			int resultjiema1=Integer.parseInt(sb.toString(),2);
			resultjiema1=resultjiema1-b;		
			aresultjiema = Integer.toBinaryString(resultjiema1);
			for(int i=0;i<resultweishu.length;i++) {
				sb1.append(resultweishu[i]);			
				}
			aresultweishu = sb1.toString();	
			//System.out.println(aresultweishu);
			if(aresultjiema.startsWith("1"))
			{
					int tmep3[] =new int[aresultjiema.length()-2];
					int temp4[] =new int[aresultjiema.length()-2];
					for(int t=0;t<tmep3.length;t++) {
						tmep3[t]=aresultjiema.charAt(t+2)-48;
						if(tmep3[t]==0) tmep3[t]=1;
						else tmep3[t]=0;
						if(t==(tmep3.length-1)) temp4[t]=1;
						else temp4[t]=0;
					}
					tmep3=binPlus(tmep3,temp4);
					StringBuffer sb2 = new StringBuffer();
					for(int i=0;i<tmep3.length;i++) {
						sb2.append(tmep3[i]);			
						}
					aresultjiema = sb2.toString();
					aresultjiema = "-"+aresultjiema;
			}
			else {
				aresultjiema = "+"+aresultjiema.substring(2,aresultjiema.length());
			}
			
			System.out.println(aresultjiema);
			
			if(aresultweishu.startsWith("0")) {
				aresultweishu = "+0."+aresultweishu.substring(2,aresultweishu.length());
			}
			else {
				int s[] =new int[aresultweishu.length()-2];
				int d[] =new int[aresultweishu.length()-2];
				for(int t=0;t<s.length;t++) {
					s[t]=aresultweishu.charAt(t+2)-48;
					if(s[t]==0) s[t]=1;
					else s[t]=0;
					if(t==(s.length-1)) d[t]=1;
					else d[t]=0;
				}
				s=binPlus(s,d);
				StringBuffer sb2 = new StringBuffer();
				for(int i=0;i<s.length;i++) {
					sb2.append(s[i]);			
					}
				aresultweishu = sb2.toString();
				aresultweishu = "-0."+aresultweishu;
			}
			System.out.println(aresultweishu);	
		}  
		String str="{\"jiema\":\""+aresultjiema+"\",\"weishu\":\""+aresultweishu+"\"}";
		resp.getWriter().write(str);
	}
	
	//Shift right
	public int[] rightMove(int a[],int count) {
		for(int j=1;j<=count;j++) {
			for(int i = a.length-1;i>=1;i--) {
			a[i]=a[i-1];
			}
		}
		return a;
	}
	/**
	 * @param number Enter a string of true values with signed bits
	 * @return  Integer array with complement as result
	 */
	private int[] bumaResult(String number) {
		String result;
		int a[];
		if(number.charAt(0)=='+') {
			result = "00";
			result = result + number.substring(1, number.length());
			int arr[] = new int[result.length()];
			for(int j = 0;j<result.length();j++)
				arr[j] = (result.charAt(j))-48;
			a=arr;
		}
		else {
			result = "11";
			for(int i = 1;i<number.length();i++) {
				if(number.charAt(i)=='0')
					result = result + "1";
				else {
					result = result + "0";
				}
			}	
			int arr[] = new int[result.length()];
			for(int j = 0;j<result.length();j++)
				arr[j] = (result.charAt(j))-48;
			int lastindex = arr.length-1;
			int flag=0;
			if(arr[lastindex]==0) {
				arr[lastindex]=1;
				flag=0;
			}
			else {
					arr[lastindex]=0;
					flag=1;
				}
			for(int k=(lastindex-1);k>=0;k--) {
				arr[k]=arr[k]+flag;
				if(arr[k]==0||arr[k]==1) flag=0;
				if(arr[k]==2) {
					arr[k]=0;
					flag=1;
				}
			}
			a=arr;
		}
		return a;
	}
	/**
	 * @param number1: Signed true string
	 * @param number2    Signed true string
	 * @return Single sign complement subtraction result
	 */
	private String minusResult(String number1, String number2) {
		String result= null;
		int[] number1arr= bumaResult(number1);
		int[] number2arr= bumaResult(number2);
		for(int i=0;i<number2arr.length;i++)
		{
			if(number2arr[i]==0) number2arr[i]=1;
			else number2arr[i]=0;
		}
		int lastindex = number2arr.length-1;
		//System.out.println(arr[lastindex]);//0
		int flag=0;
		if(number2arr[lastindex]==0) {
			number2arr[lastindex]=1;
			flag=0;
		}
		else {
			number2arr[lastindex]=0;
				flag=1;
			}
		for(int k=(lastindex-1);k>=0;k--) {
			number2arr[k]=number2arr[k]+flag;
			if(number2arr[k]==0||number2arr[k]==1) flag=0;
			if(number2arr[k]==2) {
				number2arr[k]=0;
				flag=1;
			}
		}
		int[] resultarr=binPlus(number1arr,number2arr);
		if(resultarr[0]==0) result="+";
		if(resultarr[0]==1) result="-";
		StringBuffer sb = new StringBuffer();		
		for(int m=1;m<resultarr.length;m++)
			sb.append(resultarr[m]);
		result = result + sb.toString();
		//System.out.println(result);
		return result;	
   }		
	/**
	 * @param number1arr  Binary integer array
	 * @param number2arr  Binary integer array
	 * @return Returns an integer array of binary sums
	 */
	public int[] binPlus(int[] number1arr, int[] number2arr) {
		int[] result=new int[number1arr.length];
		int flag=0;
		for (int i = (number1arr.length-1); i >=0 ; i--) {
			result[i]=number1arr[i]+number2arr[i]+flag;
			if(result[i]==0||result[i]==1) {
				flag=0;
			}
			if(result[i]==2) {
				result[i]=0;
				flag=1;
			}
			if(result[i]==3) {
				result[i]=1;
				flag=1;
			}		
		}
		return result;
	}
	
	/**
	 * @param number Enter a string of true values with signed bits
	 * @return  Integer string with result of complement
	 */
	private String buma1Result(String number) {
		String result;
		if(number.charAt(0)=='0') {
			result = "+";
			result = result + number.substring(1, number.length());
		}
		else {
			result = "-";
			for(int i = 1;i<number.length();i++) {
				if(number.charAt(i)=='0')
					result = result + "1";
				else {
					result = result + "0";
				}
			}
			//System.out.println(result.length());//5
			int arr[] = new int[result.length()-1];
//System.out.println(arr.length);//4
			for(int j = 1;j<result.length();j++)
				arr[j-1] = (result.charAt(j))-48;
			int lastindex = arr.length-1;
			//System.out.println(arr[lastindex]);//0
			int flag=0;
			if(arr[lastindex]==0) {
				arr[lastindex]=1;
				flag=0;
			}
			else {
					arr[lastindex]=0;
					flag=1;
				}
			for(int k=(lastindex-1);k>=0;k--) {
				arr[k]=arr[k]+flag;
				if(arr[k]==0||arr[k]==1) flag=0;
				if(arr[k]==2) {
					arr[k]=0;
					flag=1;
				}
			}
			result = "-";
			StringBuffer sb = new StringBuffer();
			for(int m=0;m<arr.length;m++)
				sb.append(arr[m]);
			result = result + sb.toString();
			//System.out.println(result);
		}
		return result;
	}

}
/Calculate/WebContent/css/Calculate.css
@charset "UTF-8";
html, body {
height: 100%;
overflow: auto;
}
#box {
position:relative;
padding: 0px;
margin: 30px auto;
height: 500px;
width: 650px;
background: #CAE1FF;
border-radius: 8px;
border: thin solid black;
}
#header {
width: 650px;
height: 35px;
background: white;
border-bottom: 7px solid #6495ED;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
padding: auto 1em;
color: #6495ED;
font-size: 20px;
line-height: 35px;
font-style: italic;
}
#nav ul {
display: flex;
flex-direction: row;
justify-content: space-around;
padding: 0px;
margin: 0px;
}
#nav ul li {
display: inline-block;
height: 30px;
line-height: 30px;
padding: 3px 7px;
display: inline-block;
}
#nav ul li:hover {
background-color: #6495ED;
}
.biaoti {
color: #6495ED;
font-size: 20px;
margin: 60px auto;
text-align: center;
}
#form {
box-sizing: border-box;
color: #6495ED;
margin: 100px auto;
height: 100px;
padding: 0px;
width: 100%;
text-align: center;
}
.psw {
margin-bottom: 50px;
margin-left: 30px;
}
#test1 {
margin-left:-5px;
}
#test2{
height:30px;
width:50px;
}
#calculateor {
width: 100%;
height: 100%;
margin-top: 10px;
text-align: center;
vertical-align: middle;
}
#bangzhu {
font-size: 17px;
color: black;
width:100%;
heigth:300px;
text-indent:34px;
margin-top:-45px;
line-height:20px;
}
.btns{
width:100%;
height:30px;
margin-bottom:30px;
display:flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content:space-around;
}
#jiema{
width:60%;
height:200px;
padding:0px;
}
#weishu{
}
#jw{
display:flex;
flex-flow:row nowrap;
}
/Calculate/WebContent/js/Calculate.js
$(function() {
var currentindex = 0;
$('#test2').click(function() {
var test1 = $('#test1').val();
if (test1 == '') {
alert("correct password!!" );
$('#login').css({
display : "none"
});
$('#nav').css({
display : "block"
});
$('#container>div').eq(currentindex).css({
display : "block"
});

			$('#nav>ul>li')[currentindex].style.background = '#6495ED';
			
		} else {
			alert("Password error!!");
		}
	})
	$('#nav ul>li').mouseenter(function(){
		$(this).css({
			background : "#6495ED"
		});
		
	})
	$('#nav ul>li').mouseleave(function(){
		$(this).css({
			background : "#CAE1FF"
		});
		
	})
	$('#nav ul>li').click(function() {
		$('#container>div')[currentindex].style.display = 'none';
		$('#nav ul>li')[currentindex].style.background = '#CAE1FF';
		$(this).css({
			background : "#6495ED"
		});
		var index = $(this).index();
		$('#container>div')[index].style.display = 'block';
		currentindex = index;
	})
	
	$('.in').click(function(){
		$('.inputs').val('');
		$('.inputs').focus();
	})
	
	$('.return').click(function(){
		//alert(currentindex);
		$('#login').css({
			display : "block"
		});
		$('#container>div').css({
			display : "none"
		});
		$('#nav').css({
			display : "none"
		});
		$('#test1').val('');
		$('#test1').focus();
	})
	
	$('.submit01').click(function(){
		var btnname = $(this).attr("name");
		var value = $('#ins').val();
		//alert(btnname);
		if(value=='') alert("Please enter legal data!!");
		else{
		$.ajax({
		    type:'POST',
		    url:'trueNumber',
		    async:"true",
		    dataType:'text',
		    data:{number:value,
		    	btnname:btnname	
		    },
		    success:function(data){
		        $("#outs").val(data);
		    },
		    error:function(jqXHR){
		    }
		});
		}
	})
	
	$('.submit02').click(function(){
		var btnname = $(this).attr("name");
		var value1 = $('#number1').val();
		var value2 = $('#number2').val();
		if(value1==''||value2=='') alert("Please enter legal data!!");
		//alert(btnname);
		else{
		$.ajax({
		    type:'POST',
		    url:'dzdfplus',
		    async:"true",
		    dataType:'text',
		    data:{number1:value1,
		    	number2:value2,
		    	btnname:btnname	
		    },
		    success:function(data){
		    	if(btnname=="plus"){
		    		$("#out1").val(data);
		    	}
		    	else{
		    		$("#out2").val(data);
		    	}
		    },
		    error:function(jqXHR){
		    }
		});
	  }
	})
	
	$('#submit03').click(function(){
		var value3 = $('#number3').val();
		var value4 = $('#number4').val();
		if(value3==''||value4=='') alert("Please enter legal data!!");
		//alert(btnname);
		else{
		$.ajax({
		    type:'POST',
		    url:'dzymcf',
		    async:"true",
		    dataType:'text',
		   data:{number3:value3,
		    	number4:value4,
		    },
		    success:function(data){
		    	if(data=="error")
		    		alert("Please enter the original code of the same length!!");
		    	else $("#out3").val(data);
		    },
		    error:function(jqXHR){
		    }
		});
	  }
	})
	
	$('.submit04').click(function(){
		Var btnname = $(this).attr("name");
		var jiema1 = $('#jiema1').val();
		var weishu1 = $('#weishu1').val();
		var jiema2 = $("#jiema2").val();
		var weishu2 = $("#weishu2").val();
		if(jiema1==''||weishu1==''||jiema2==''||weishu2=='') alert("Please enter legal data!!");
		else{
		$.ajax({
		    type:'POST',
		    url:'fdplusminus',
		    async:"true",
		    dataType:'text',
		    data:{
		    	jiema1:jiema1,
		    	weishu1:weishu1,
		    	jiema2:jiema2,
		    	weishu2:weishu2,
		    	btnname:btnname	
		    },
		    success:function(data){
		    	var data=JSON.parse(data);
		    	if(btnname=="plus"){
		    		//alert(data.jiema);
		    		$("#plusjiema").val(data.jiema);
		    		$("#plusweishu").val(data.weishu);
		    	}
		    	else if(btnname=="minus"){
		    		$("#minusjiema").val(data.jiema);
		    		$("#minusweishu").val(data.weishu);
		    	}			    	
		    },
		    error:function(jqXHR){
		    }
		});
		}
	})	})

Topics: Java JQuery JSP less