2

It is possible to convert 24 bit integer value into float and then back to 24 bit integer without losing data?

For example, let's consider 8 bit int, a byte, range is [-127..127] (we drop -128).

public static float ToFloatSample (byte x) { return x / 127f; }

So, if x == -127, result will be -1, if x == 127, result will be 1. If x == 64, result will be ~0.5

public static int ToIntSample (float x) { return (int) (x * 127f); }

So now:

int x = some_number;
float f = ToFloatSample (x);
int y = ToIntSample (f);

Will always x == y ? Using 8 bit int yes, but what if I use 24 bit?

apocalypse
  • 5,764
  • 9
  • 47
  • 95

2 Answers2

1

Having thought about your question, I now understand what you're asking.

I understand you have 24-bits which represent a real number n such that -1 <= n <= +1 and you want to load this into an instance of System.Single, and back again.

In C/C++ this is actually quite easy with the frexp and ldexp functions, documented here ( how can I extract the mantissa of a double ), but in .NET it's a more involved process.

The C# language specification (and thusly, .NET) states it uses IEEE-754 1989 format, which means you'll need to dump the bits into an integer type so you can perform the bitwise logic to extract the components. This question has already been asked here on SO except for System.Double instead of System.Single, but converting the answer to work with Single is a trivial exercise for the reader ( extracting mantissa and exponent from double in c# ).

In your case, you'd want to store your 24-bit mantissa value in the low-24 bits of an Int32 and then use the code in that linked question to load and extract it from a Single instance.

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
1

Every integer in the range [-16777216, 16777216] is exactly representable as an IEEE 754 32-bit binary floating point number. That includes both the unsigned and 2's complement 24 bit integer ranges. Simple casting will do the job.

The range is wider than you would expect because there is an extra significand bit that is not stored - it is a binary digit that is known not to be zero.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • 1
    The OP says he wants to store numbers between `-1` to `+1`, so not integers. Casting won't work in his case. – Dai Sep 16 '14 at 20:26