當我需要將基於10
的IEEE-754單精度和雙精度數字轉換爲字符串時,我已進入狀態。有FXTRACT
指令可用,但它僅提供指數和尾數爲基數2,如數量,計算公式爲:將浮動字符串轉換爲字符串
value = (-1)^sign * 1.(mantissa) * 2^(exponent-bias)
如果我有特定的鹼基一些對數的說明,我將能夠改變的2基地指數 - 偏差部分表達,但目前我不知道該怎麼辦。我也在考慮使用標準的四捨五入轉換爲整數,但它似乎無法使用,因爲它不提供精確的轉換。有沒有人知道這樣做的基本原理是什麼?請幫忙。
我終於找到了另一種解決方案(這是在Java中)
{
/* handling -infinity, +infinity and NaN, returns "" if 'f' isn't one of mentioned */
String ret = "";
if ((ret = getSpecialFloats(f)).length() != 0)
return ret;
}
int num = Float.toRawIntBits(f);
int exponent = (int)(((num >> 23) & 0xFF)-127); //8bits, bias 127
int mantissa = num & 0x7FFFFF; //23bits
/* stores decimal exponent */
int decimalExponent = 0;
/* temporary value used for calculations */
int sideMultiplicator = 1;
for (; exponent > 0; exponent--) {
/* In this loop I'm calculating the value of exponent. MAX(unsigned int) = 2^32-1, while exponent can be 2^127 pr st like that */
sideMultiplicator *= 2;
/* because of this, if top two bits of sideMultiplicator are set, we're getting closer to overflow and we need to save some value into decimalExponent*/
if ((sideMultiplicator >> 30) != 0) {
decimalExponent += 3;
sideMultiplicator /= 1000;
}
}
for(; exponent < 0; exponent++) {
/* this loop does exactly same thing as the loop before, but vice versa (for exponent < 0, like 2^-3 and so on) */
if ((sideMultiplicator & 1) != 0) {
sideMultiplicator *= 10;
decimalExponent--;
}
sideMultiplicator /= 2;
}
/* we know that value of float is:
* 1.mantissa * 2^exponent * (-1)^sign */
/* that's why we need to store 1 in betweenResult (another temorary value) */
int betweenResult = sideMultiplicator;
for (int fraction = 2, bit = 0; bit < 23; bit++, fraction *= 2) {
/* this loop is the most important one: it turns binary mantissa to real value by dividing what we got in exponent */
if (((mantissa >> (22-bit)) & 1) == 1) {
/* if mantissa[bit] is set, we need to divide whole number by fraction (fraction is 2^(bit+1)) */
while (sideMultiplicator % fraction > 0 && (betweenResult >> 28) == 0) {
/* as we needed it before: if number gets near to overflow, store something in decimalExponent*/
betweenResult *= 10;
sideMultiplicator *= 10;
decimalExponent--;
}
betweenResult += sideMultiplicator/fraction;
}
}
/* small normalization turning numbers like 15700 in betweenResult into 157e2 (storing zero padding in decimalExponent variable)*/
while (betweenResult % 10 == 0) {
betweenResult /= 10;
decimalExponent++;
}
/* this method gets string in reqested notation (scientific, multiplication by ten or just normal)*/
return getExponentedString(betweenResult, decimalExponent);
爲什麼不鏈接到標準C庫並調用'printf'或'sprintf'? –
http://stackoverflow.com/questions/22962040/easiest-way-to-convert-a-decimal-float-to-bit-representation-manually-based-on-i和http:// stackoverflow的副本。com/questions/23540139/how-to-convert-floating-point-number-to-ieee-754-using-assembly –
這很難做到這一點,並且@PascalCuoq已經寫了一個[blog](http: /www.exploringbinary.com/correct-decimal-to-floating-point-using-big-integers/)關於此 –