問題描述
是的,我知道 IEEE-754 半精度標準,是的,我知道在該領域所做的工作.簡而言之,我試圖將一個簡單的浮點數(如 52.1
或 1.25
)保存在 2 個字節中.
Yes I'm aware of the IEEE-754 half-precision standard, and yes I'm aware of the work done in the field. Put very simply, I'm trying to save a simple floating point number (like 52.1
, or 1.25
) in just 2 bytes.
我在 Java 和 C# 但它們通過解碼不同的數字來破壞輸入值.您輸入 32.1
并在編碼解碼后得到 32.0985
.
I've tried some implementations in Java and in C# but they ruin the input value by decoding a different number. You feed in 32.1
and after encode-decode you get 32.0985
.
有什么方法可以在不破壞輸入值的情況下以 16 位存儲浮點數?
Is there ANY way I can store floating point numbers in just 16-bits without ruining the input value?
非常感謝.
推薦答案
您可以將三位數字存儲為 BCD 并使用剩余的四位作為小數點位置:
You could store three digits in BCD and use the remaining four bits for the decimal point position:
52.1 = 521 * 10 ^ -1 => 0x1521
1.25 = 125 * 10 ^ -2 => 0x2125
這將為您提供從 0.0000000000000001 到 999 的范圍.當然,您可以為小數點添加偏移量,例如范圍為 0.0000000001 到 999000000.
This would give you a range from 0.0000000000000001 to 999. You can of course add an offset for the decimal point to get for example the range 0.0000000001 to 999000000.
四位用于小數點放置的簡單實現,其余用于值.沒有任何錯誤檢查,也沒有徹底檢查.(使用 !=
比較雙精度時,某些值可能存在精度問題.)
Simple implementation of four bit used for decimal point placement, and the rest for the value. Without any error check, and not thoroughly checked. (May have precision issues with some values when using !=
to compare doubles.)
public static short Encode(double value) {
int cnt = 0;
while (value != Math.Floor(value)) {
value *= 10.0;
cnt++;
}
return (short)((cnt << 12) + (int)value);
}
public static double Decode(short value) {
int cnt = value >> 12;
double result = value & 0xfff;
while (cnt > 0) {
result /= 10.0;
cnt--;
}
return result;
}
例子:
Console.WriteLine(Encode(52.1));
Console.WriteLine(Decode(4617));
輸出:
4617
52.1
這篇關于如何將浮點數保存為 2 個字節?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!