关于字符串二进制定点数浮点数与int以及NBCD码转换的问题

关于字符串二进制定点数浮点数与int以及NBCD码转换的问题(代码)

  1. 将十进制数字字符串转化为二进制补码(32位):
public String intToBinary(String numStr) {
        int num = Integer.parseInt(numStr);        
        if (num == 0) return "00000000000000000000000000000000";  //0单独判读              
        boolean isNeg = false;        
        if (num < 0) {  //负数转正数            
        num = -num;            
        isNeg = true;        
        }        
        StringBuilder temp = new StringBuilder();        
        while (num > 0) {  //转为二进制            
        if (num % 2 == 1) temp.append("1");            
        else temp.append("0");            
        num /= 2;        }        
        String ans = temp.reverse().toString();  //反转,从低位开始计算        
        int len = ans.length();        
        for (int i = 0; i < 32 - len; i++) ans = "0" + ans;        
        if (isNeg) {  //如果是负数那么取反加一            
        ans = oneAdder(negation(ans)).substring(1);        
        }        
        return ans;    
        }

进位判断(第一位判断是否溢出)

private String oneAdder(String operand) {
        int len = operand.length();        
        StringBuffer temp = new StringBuffer(operand);        
        temp = temp.reverse();//只是将位反转,因为要从低位到高位加一        
        int[] num = new int[len];        
        for (int i = 0; i < len; i++) num[i] = temp.charAt(i) - '0';  // 先转化为反转后对应的int数组        
        int bit = 0x0;        
        int carry = 0x1;        
        char[] res = new char[len];        
        for (int i = 0; i < len; i++) {            
        bit = num[i] ^ carry;            
        carry = num[i] & carry;            
        res[i] = (char) ('0' + bit);  // 显示转化为char        
        }        
        String result = new StringBuffer(new String(res)).reverse().toString();        
        return "" + (result.charAt(0) == operand.charAt(0) ? '0' : '1') +result;  // 注意有进位不等于溢出,溢出要另外判断   
         }

将负数二进制取反

private String negation(String operand) {
        StringBuffer result = new StringBuffer();        
        for (int i = 0; i < operand.length(); i++) {            
        result = operand.charAt(i) == '1' ? result.append("0") : 
        result.append("1");        
        }        
        return result.toString();    
        }
  1. 将二进制(字符串)转化为十进制(直接使用库中的方法):
public String binaryToInt(String binStr) {
        return String.valueOf(valueOf(binStr, 2));
            }
  1. 将十进制浮点数转化为32位单精度浮点数(较为困难,主要原因:需要判断能否表示):
public String floatToBinary(String floatStr) {
        int eLength = 8;//指数位        
        int sLength = 23;//浮点数
        double d = Double.valueOf(floatStr);        
        boolean isNeg = d < 0;
        if (Double.isNaN(d)) {            
        return "Nan";        }        
        if(!isFinite(d, eLength, sLength)){
                    return isNeg ? "-Inf" : "+Inf";        }
        StringBuilder answer = new StringBuilder(1+eLength+sLength);
        if(isNeg) answer.append("1");
        else answer.append("0");
        if(d == 0.0) {            
            for(int i=0;i<eLength+sLength;i++){
                        answer.append("0");            }            
                        return answer.toString();        } 
                        else {           
                         d = Math.abs(d);          
                           int bias = (int)((maxValue(eLength)+1)/2-1);  // bias            
                           boolean subnormal = (d < minNormal(eLength,sLength));
            if(subnormal){                
            for(int i=0;i<eLength;i++){                    
            answer.append("0");                }                
            d = d * Math.pow(2, bias-1);  //将指数消去
                answer.append(fixPoint(d, sLength));            }            
                else{
                int exponent = (int)getExponent(d);          
                answer.append(integerRepresentation(String.valueOf((int(exponent+bias)),eLength));  // 加上 bias                d = d / Math.pow(2, exponent);
                answer.append(fixPoint(d-1, sLength));  // fixPoint传入的参数要求小于1,自动忽略了隐藏位            }      
                  }        return answer.toString();  
                    }

补全32位

private String integerRepresentation(String number, int length) {
        String result = intToBinary(number);        
        return result.substring(32 - length);    }

判断浮点数能否用二进制表示(IEEE754标准有表示的范围)

private boolean isFinite(double d, int eLength, int sLength) {
        int bias = (int) ((maxValue(eLength) + 1) / 2 - 1);  // bias        
        int exponent = (int) (maxValue(eLength) - 1 - bias - sLength);  // 指数全1和全0是特殊情况,这里只要计算可以被正常表示的最大值,因此-1,且直接将significand转化的位数减去        
        double significand = maxValue(sLength + 1);  // 加上隐藏位        
        double result = significand * Math.pow(2, exponent);       
         return d >= -result && d <= result;    }

计算能表示的最大的浮点数

private double maxValue(int length) {
        //不能使用移位操作        
        return Math.pow(2, length) - 1;    }

计算能表示的最小的浮点数

private double minNormal(int eLength, int sLength) {
        int bias = (int) ((maxValue(eLength) + 1) / 2 - 1);  // bias        return Math.pow(2, 1 - bias);  // 指数为1,阶码全0    }

不动点

private String fixPoint(double d, int sLength) {
        d = d < 1 ? d : d - (int) d;  // d = 0.xxxxx       
         StringBuilder res = new StringBuilder();        
         int count = 0;        
         while (d != 0 && count < sLength) {           
          d *= 2;            
          if (d < 1) {                
          res.append("0");            } 
          else {                
          d -= 1;                
          res.append("1");            }            
          count++;  // 最长为sLength的长度        }        
          int len = res.length();  // 不能直接用res.length()       
           for (int i = 0; i < sLength - len; i++) res.append(0);        
           return res.toString();    }
  1. 将二进制浮点数转化为十进制浮点数
public String binaryToFloat(String binStr) {
        boolean isNeg = (binStr.charAt(0) == '1');        
        String exp = binStr.substring(1, 9);        
        String frag = binStr.substring(9);
        if (exp.equals("11111111")) {            
        if (frag.contains("1")) {                
        return "NaN";            } 
        else {               
         return isNeg ? "-Inf" : "+Inf";            }        }
          else if (exp.equals("00000000")) {            
          if (frag.contains("1")) {               
           double f = 0.0;                
           int fe = 1;                
           for (char fc:frag.toCharArray()) {                    
           f += Integer.parseInt(String.valueOf(fc)) / Math.pow(2, fe);                    
           fe++;                }                
           f = (f)*Math.pow(2, -126);               
            f = isNeg ? -f : f;               
             return String.valueOf(f);            } 
             else {                return "0.0";            }        }
                    double f = 0.0;        
                    int fe = 1;        
                    for (char fc:frag.toCharArray()) {            
                    f += Integer.parseInt(String.valueOf(fc)) / Math.pow(2, fe);            
                    fe++;        }
                     int e = valueOf(exp, 2) - 127;       
                      f = (1+f)*Math.pow(2, e);        
                      f = isNeg ? -f : f;
                      return String.valueOf(f);    }
  1. 将十进制转化为NBCD码
public String decimalToNBCD(String decimal) {       
 return getBCDString(Integer.parseInt(decimal));    }
public String getBCDString(int val) {
        String sign = val < 0 ? "1101" : "1100"; //得到符号位       
         String result = "";        
         val = Math.abs(val);        
         int i = 7;        
         while (i > 0) {            
         int tmpVal = val % 10;            
         result = getBCDString_4(tmpVal).concat(result);            
         val = val / 10;            
         i--;        }        
         return sign.concat(result);    }
  1. 将NBCD码转化为十进制
public String NBCDToDecimal(String NBCDStr) {
        return String.valueOf(NBCDTrueValue(NBCDStr));    }
private int NBCDTrueValue(String operand) {
        StringBuilder ans = new StringBuilder();        
        if (operand.startsWith("1101")) ans.append('-');        
        operand = operand.substring(4);        
        for (int i = 0; i < operand.length() && i < 28; i += 4) {
           ans.append(Integer.valueOf(operand.substring(i, i + 4), 2));        }        
           return Integer.parseInt(ans.toString());    }

你可能感兴趣的:(计算机组成与结构)