程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 進制轉換-java中如何從double類型轉為二進制數

進制轉換-java中如何從double類型轉為二進制數

編輯:編程解疑
java中如何從double類型轉為二進制數

固定精度的double類型數如何轉為24位二進制數 。

最佳回答:


/** * 十進制數轉二進制數 * @param d 十進制數 * @return 十進制數轉換成二進制的字符串 / public String decimal2BinaryStr(double d){ String result = decimal2BinaryStr_Inte(d); result += decimal2BinaryStr_Deci(d); return result; } /* * 十進制整數部分轉二進制數 * @param d 十進制數 * @return 十進制整數部分轉換成二進制的字符串 / public String decimal2BinaryStr_Inte(double d){ // return Integer.toBinaryString((int)d); / * 本來利用上面的Integer.toBinaryString(int)就可以得到整數部分的二進制結果, * 但為了展示十進制轉二進制的算法,現選擇以下程序來進行轉換 / String result = ""; long inte = (long)d; int index = 0; while(true){ result += inte%2; inte = inte/2; index++; if(index%4 == 0){ result+=" "; } if(inte==0){ while(index%4!=0){ result+="0"; index++; } break; } } char[] c = result.toCharArray(); char[] cc = new char[c.length]; for(int i=c.length; i>0; i--){ cc[cc.length-i] = c[i-1]; } return new String(cc); } /* * 十進制小數部分轉二進制 * @param d 十進制數 * @return 十進制小數部分轉換成二進制小數的字符串 / public String decimal2BinaryStr_Deci(double d){ return decimal2BinaryStr_Deci(d, 0); } /* * 十進制小數部分轉二進制 * @param d 十進制數 * @param scale 小數部分精確的位數 * @return 十進制小數部分轉換成二進制小數的字符串 */ public String decimal2BinaryStr_Deci(double d, int scale){ double deci = sub(d,(long)d); if(deci==0){ return ""; } //為了防止程序因所轉換的數據轉換後的結果是一個無限循環的二進制小數,因此給其一個默認的精確度 if(scale==0){ scale = (String.valueOf(deci).length()-2)*4; } int index = 0; StringBuilder inteStr = new StringBuilder(); double tempD = 0.d; while(true){ if(deci==0 || index==scale){ while(index%4!=0){ inteStr.append("0"); index++; } break; } if(index==0){ inteStr.append("."); } tempD = deci*2; inteStr.append((int)tempD); deci = sub(tempD ,(int)tempD); index++; if(index%4 == 0){ inteStr.append(" "); } } return inteStr.toString(); }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved