Using java to realize the mutual conversion mechanism of decimal and binary decimals

Using java to realize the mutual conversion mechanism of decimal and binary decimals

  This blog mainly describes the use of java to realize the mutual conversion of decimal and binary decimals (without calling the functions that come with java). It may be implemented in MATLAB later, because one of our information security experiments is required to be implemented in MATLAB.

Require

An experiment in the information security course requires
1. Write a program to realize the binary conversion of decimal fraction x=0.7, and analyze the error (that is, re-convert the binary decimal to a decimal fraction, and compare it with the original decimal number.)
2. Program to realize the decimal number Binary conversion of x=5.9.

ideas

  The idea of ​​the second sub-question is to divide the decimal into integer part and fractional part to achieve.

accomplish

MATLAB implementation

%%
clear
clc
n=0.7;
m=20;%保留10位小数
%将十进制乘以2用floor取整,接着用其余数进行循环操作
d=char(mod(floor(n*2.^(1:m)),2)+'0');%char函数创建一个字符矩阵
d1=[d(1:end-m),'.',d(end-m+1:end)]%显示二进制转换小数
f=d-'0';
f1=sum(f./(2.^(1:m)))   %% 二进制转换十进制
error = n-f1

Java language implementation
Execution environment: JDK1.8, IntelliJ IDEA 2017.3.4 x64.

import static java.lang.System.out;
/**
 * 实现二进制与十进制的互换
 * @author Canlong
 * @time 2018/4/13
 */
public class Test3 {

    /**
     * 1、 编写程序实现十进制小数x=0.7 的二进制转换,并分析其误差(即重新将二进制小数转成十进制小数,和原十进制小数进行比较。)
     2、编程实现十进制数 x=5.9的二进制转换。
     * @param args
     */
    public static void main(String[] args){
    //要转化的十进制小数
        double x = 0.7;
        //将十进制小数转化为二进制
        String binXStr = decXiao2Bin(x);
        //将二进制小数转化为十进制
        double decX = bin2DecXiao(binXStr);
        out.println("误差为:"+(x-decX));

        //将十进制数转化为二进制
        double decX1 = 5.9;
        int decInt = (int) Math.floor(decX1);
        double decXiao = decX1-decInt;
        String  binInt = decInt2Bin(decInt);
        String binX = decXiao2Bin(decXiao);
        out.println("5对应的二进制为:"+binInt);
        out.println("5.9对应的二进制为:"+binInt+"."+binX);
    }
    //将十进制整数转换为二进制
    public static String decInt2Bin(int decInt){
        int index = 0;
        int rem = 1;
        String binStr="";
        while(decInt!=1){
            rem = decInt%2;
            decInt = decInt/2;
            binStr += Integer.toString(rem);
            if(decInt == 1){
               binStr+=Integer.toString(decInt);
            }
        }
        return binStr;
    }

    /**
     * 将十进制小数转化为二进制
     */
    public static String decXiao2Bin(double x){
        //精确位数
        int accurate = 100;
        int[] binX = new int[accurate];
        String binXSB="";
        double x1 = x;
        double x2=0;
        for(int i=0;i<binX.length;i++){
            x2 = x1+x1;
            x1 =Math.floor(x2);
            binX[i]=(int)x1;
            x1=x2-x1;
            binXSB += Integer.toString(binX[i]);
        }
        String binXStr = binXSB.toString();
        out.println(x+"的近似二进制数为(精确到小数点后"+accurate+"位):"+binXStr);
        return  binXStr;
    }

    /**
     * 将二进制小数转化为十进制
     * @param binXStr 二进制小数
     * @return 十进制小数
     */
    public static double bin2DecXiao(String binXStr){
        double decX = 0.0;
        //位数
        int k =0;
        for(int i=0;i<binXStr.length();i++){
            int exp = binXStr.charAt(i)-'0';
            exp = -(i+1)*exp;
            if(exp!=0) {
                decX += Math.pow(2, exp);
            }
        }
        out.println("二进制小数为;"+binXStr+"。\r\n其对应的十进制为:"+decX);
        return decX;
    }
}

result

write picture description here

Error analysis:
  After testing many times, the java code and matlab convert decimal decimals to binary decimals. If double is used for storage, it can only be converted to binary to 53 decimal places at most, and the numbers after that are all 0. Moreover, due to the value of double type, java can only store up to 16 decimal places. As long as it is within this range, using the above conversion code, the error generated is 0. As for why the use of arrays to store binary can only be stored to the last 53 bits of the binary number, the reason remains to be explored. It is initially suspected that due to the constant subtraction of the integer part when the decimal decimal is converted into a binary decimal, the fractional part is eventually very small. Even if it has been doubled many times, it still cannot reach 1, or the binary decimal with the largest number of decimals stored by the computer is 53 digits after the decimal point. .
  Later, after outputting the converted decimal fraction of each step, it was found that every time around the 50th step, the decimal fraction became 0.5, so the reason should be that as long as the decimal fraction is within 16 decimal places, it can be doubled by 50 times ( remove the integer part before doubling) becomes 0.

Summarize

  In general, this implementation is not too difficult, but because of my unfamiliarity with the operation of the method, I wrote a lot of redundant code and wasted a lot of time to complete this classroom experiment. Next time you have the opportunity to improve it. As for the principle of implementation, I will talk about it next time when I have the opportunity. In fact, there are functions in java to realize the exchange of decimal and binary, but after implementing the conversion between binary and decimal from the principle level, I can exercise my thinking ability. After this practice, I found that I am not too familiar with the theory of binary and decimal conversion, and Java is also extremely inefficient. However, after this practice, my understanding of the theoretical and practical parts of this conversion has deepened a lot, and I will continue to study it later.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684252&siteId=291194637