如何保存在2个字节的浮点数? [英] How do I save a floating-point number in 2 bytes?

查看:3538
本文介绍了如何保存在2个字节的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我知道的IEEE-754半precision标准的,是的,我知道在场上所做的工作。非常简单的说,我试图挽救一个简单的浮点数(如 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 和连接code-DE code你以后 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码,并使用剩余的4位为小数点位置:

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到9.99亿。

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.

简单实现用于小数点位置四位的,其余​​的值。没有任何错误检查,并没有彻底检查。 (可使用时,有一些值precision问题!= 比较双打)。

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个字节的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆