⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fastfloat16.c

📁 ADI BF 16位定点DSP的快速浮点仿真的汇编代码
💻 C
字号:
#include <math.h>
#include <fract.h>

#include "FastFloat.h"

fastfloat16 float_to_ff16(float flt) {
	int *f = (int *)&flt;
	fastfloat16 ff;
	unsigned short exp;
	unsigned short frac;
  unsigned short sb = 0;
  
	sb = ((*f)>>31 & 0x1); // isolate the sign bit
  exp =((*f)>>23 & 0xFF); // isolate the exponent  
	frac = ((*f)>>7 & 0xFFFF); // isolate the mantissa (and shift to make sure it fits in a 16-bit word)

	switch(exp) {
    case 255:
      ///printf("E=255\n");
      if (frac) {
        ///printf("NaN\n");
      }
      if (!frac && sb) {
        ///printf("-inf\n");
      }
      if (!frac && !sb) {
        ///printf("+inf\n");
      }      
      break;
    case 0:
      ///printf("E=0\n");
      if (frac) {
        ///printf("unnormalized\n");
        ff.exp = -126;
        ff.frac = frac>>1;
        if (sb) {
          ff.frac *= -1;
        }
      }
      if (!frac && sb) {
        ///printf("-0\n");
        ff.exp = 0;
        ff.frac = 0;
      }
      if (!frac && !sb) {
        ///printf("+0\n");
        ff.exp = 0;
        ff.frac = 0;
      }             
      break;
    default:
      ///printf("0<E<255\n");
      ///printf("normalized\n");
      ff.exp = exp - 127 + 1; // add 1 to denormalize the mantissa
      ff.frac = ((frac>>2) | 0x4000);
      if (sb) {
        ff.frac *= -1;
      }
      break; 
	}
	return ff;
}

float ff16_to_float(fastfloat16 ff) {	
	float flt;
	short exp;
	short frac;
  short sb = 0x0;
  int leading_zeros;
  
	int *f = (int *)(&flt);

	// special case for zero
	if ((ff.frac & 0xFFFF) == 0x0000) {
    return 0.0;
  }

	frac = ff.frac;

	// special case, because you can't take a 2's complement of -1
	if ((frac & 0xFFFF) == 0x8000) {
    ff.exp = ff.exp + 1;
    frac = ff.frac >> 1;
	}
	
	// case where the mantissa is negative
  if (frac < 0) {     
    sb = 0x1;
    frac = frac * -1;
  }

  // the following two lines are equivalent; they extract the number of leading zeros  
  leading_zeros = norm_fr1x16(frac) + 1;
  //asm("%0 = signbits %1;" : "=l" (leading_zeros) : "l" (frac));

  // adjust the exponent
  exp = ((ff.exp) + 127 - leading_zeros);
  if (exp <= 0) { // check for unnormalized case
    frac = frac<<(leading_zeros+exp);
    exp = 0;
  }
  else { // no normalization necessary
    frac = frac<<(leading_zeros+1);
  }
  
  *f = sb<<31; // place the sign bit in its location
 	*f = *f | (frac & 0xFFFF)<<7; // mask in mantissa
  *f = *f | (exp << 23); // shift in exponent    

  return flt;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -