37 lines
1.3 KiB
C
37 lines
1.3 KiB
C
#include <stdint.h>
|
|
#include <float16.h>
|
|
#include <math.h>
|
|
|
|
// Helper function to convert float16 to float (from StackOverflow)
|
|
float float16_to_float(uint16_t float16_val) {
|
|
// Implement the IEEE-754 FP16 decoding logic here.
|
|
// See: https://stackoverflow.com/a/60047308
|
|
// Example placeholder (replace with actual implementation):
|
|
uint32_t sign = (float16_val & 0x8000) << 16;
|
|
uint32_t exponent = (float16_val & 0x7C00) >> 10;
|
|
uint32_t mantissa = float16_val & 0x03FF;
|
|
|
|
if (exponent == 0) {
|
|
// Subnormal or zero
|
|
return (sign ? -1.0f : 1.0f) * powf(2.0f, -14.0f) * (mantissa / 1024.0f);
|
|
} else if (exponent == 0x1F) {
|
|
// Infinity or NaN (not supported in Refloat, per docs)
|
|
return sign ? -INFINITY : INFINITY;
|
|
} else {
|
|
// Normalized number
|
|
return (sign ? -1.0f : 1.0f) * powf(2.0f, exponent - 15.0f) * (1.0f + mantissa / 1024.0f);
|
|
}
|
|
}
|
|
|
|
// Convert Refloat float16 to int16_t (scaled by 10)
|
|
int16_t refloat_float16_to_int16_scaled(uint16_t float16_val) {
|
|
float float_val = float16_to_float(float16_val);
|
|
float scaled_val = float_val * 10.0f;
|
|
|
|
// Clamp to int16_t range to avoid overflow
|
|
if (scaled_val > 32767.0f) return 32767;
|
|
if (scaled_val < -32768.0f) return -32768;
|
|
|
|
return (int16_t)scaled_val;
|
|
}
|