1. 程式人生 > >單精度浮點數操作

單精度浮點數操作

加法 precision n) ack mil ring oid www creat

用數組存儲32位單精度浮點數,並且實現有效位右移,有效數加法等,可用於計算機浮點加減法的底層模擬。

  1 package com.computerOrganizationAndArchitecture.floatQperation;
  2 
  3 import com.computerOrganizationAndArchitecture.singleprecisionfloat.SinglePrecision;
  4 
  5 /**
  6  * Created by XuTao on 2018/12/8 20:24
  7  * 這裏用數組來存儲32位的浮點數,
  8  */
  9 public
class BinaryArray { 10 protected int [] binArr; 11 private int len; 12 public BinaryArray(){ 13 len = 32; 14 binArr = new int[32]; 15 } 16 public BinaryArray(String s){ 17 len =32; 18 binArr = new int[32]; 19 for (int i =0 ;i<32;i++){
20 binArr[i] = s.charAt(i)==‘1‘?1:0; 21 } 22 } 23 public BinaryArray(String s,int len){ //自定義長度 24 this.len =len; 25 binArr = new int[len]; 26 for (int i =0 ;i<len;i++){ 27 binArr[i] = s.charAt(i)==‘1‘?1:0; 28 } 29 }
30 public BinaryArray(double n){ 31 len =32; 32 binArr = new int[32]; 33 String ss= new SinglePrecision().Float2Binary(n);//https://www.cnblogs.com/XT-xutao/p/9906351.html 34 String s= ss.charAt(0)+ss.substring(2,10)+ss.substring(11); 35 for (int i =0 ;i<32;i++){ 36 binArr[i] = s.charAt(i)==‘1‘?1:0; 37 } 38 } 39 40 public void shiftRight(int n){//右移n位 41 int [] temp = new int[n]; 42 for (int i=23;i>=n;i--){//移動 43 binArr[i]=binArr[i-n]; 44 } 45 for (int i=0;i<n;i++){//補0 46 binArr[i]=0; 47 } 48 } 49 public String toString(){ 50 String s= ""; 51 for (int i =0;i<len;i++){ 52 s+=binArr[i]; 53 } 54 return s; 55 } 56 public String toString(int []binArr){ 57 String s= ""; 58 for (int i =0;i<binArr.length;i++){ 59 s+=binArr[i]; 60 } 61 return s; 62 } 63 public String toExpString(){ 64 String s= ""; 65 for (int i =1;i<9;i++){ 66 s+=binArr[i]; 67 } 68 return s; 69 } 70 public String toSignificandString(){ // 24位的 71 String s= ""; 72 for (int i =9;i<len;i++){ 73 s+=binArr[i]; 74 } 75 return "1"+s; 76 } 77 public int getExp (){ 78 return Integer.valueOf(toExpString(),2); 79 } 80 81 public static int[] add(String a,String b){//N位二進制+1位進位(0/1)相加 =N+1位 82 //a,b長度要相等 83 int [] temp = new int[a.length()+1]; 84 int [] arr1 = (new BinaryArray(a,a.length())).binArr; 85 int [] arr2 = (new BinaryArray(b,b.length())).binArr; 86 int carry = 0; 87 for (int i =a.length()-1;i>=0;i--){ 88 temp[i+1] = arr1[i]+arr2[i]+carry; 89 carry=0; 90 if (temp[i+1]==2){ 91 temp[i+1]=0; 92 carry = 1; 93 } 94 if (temp[i+1]==3){ 95 temp[i+1]=1; 96 carry = 1; 97 } 98 } 99 //最高位進位 100 temp[0] = carry==1?1:0; 101 return temp; 102 } 103 104 public int[] getNegative(){ 105 int [] temp = new int[32]; 106 for (int i=0;i<32;i++){ 107 108 } 109 return temp; 110 } 111 112 public static void main(String[] args) { 113 BinaryArray ba = new BinaryArray(-879.5); 114 System.out.println(ba.toString()); 115 //11000100 01011011 11100000 00000000 116 System.out.println(ba.toSignificandString()); 117 118 } 119 120 }

單精度浮點數操作