본문 바로가기

Programing/C

float32bit ↔ float16bit 변환

float 32bit  https://en.wikipedia.org/wiki/Single-precision_floating-point_format

 

Single-precision floating-point format - Wikipedia

From Wikipedia, the free encyclopedia 32-bit computer number format Single-precision floating-point format (sometimes called FP32 or float32) is a computer number format, usually occupying 32 bits in computer memory; it represents a wide dynamic range of n

en.wikipedia.org

 

float 16bit  https://en.wikipedia.org/wiki/Half-precision_floating-point_format

 

Half-precision floating-point format - Wikipedia

From Wikipedia, the free encyclopedia 16-bit computer number format Not to be confused with bfloat16, a different 16-bit floating-point format. In computing, half precision (sometimes called FP16 or float16) is a binary floating-point computer number forma

en.wikipedia.org

 

  sign exponent fraction
float 16bit 1 bit 5 bit(-0xF) 10 bit (2^10)
float 32bit 1 bit 8 bit(-0x7F) 23 bit (2^23)
union float_32 {
  float dataf;
  uint32_t data32;
};
uint16_t float32To16(uint32_t _num) {
  // float 32bit : 1bit sign, 8bit exponent, 23bit fraction
  // float 16bit : 1bit sign, 5bit exponent, 10bit fraction
  uint16_t sign = (_num >> 16) & 0x8000;
  int16_t exponent = (_num >> 23) & 0xFF;
  uint32_t fraction = (_num & 0x7FFFFF);

  fraction = (fraction / 8192) & 0x3FF;  // 8192 = pow(2,23) / pow(2,10)

  if(exponent == 0x00) {
    exponent = 0x00;
  }else if(exponent == 0xFF) {
    exponent = 0x1F;
  }else {
    exponent -= 0x7F;
    if(exponent < -127 || 128 < exponent) {
      // Error 지수 범위 초과
      exponent = 0x1F;
      fraction = 0x0000;
    }else {
      exponent += 0xF;
    }
  }
  return (sign | (exponent << 10) | fraction);
}
uint32_t float16To32(uint16_t _num) {
  // float 32bit : 1bit sign, 8bit exponent, 23bit fraction
  // float 16bit : 1bit sign, 5bit exponent, 10bit fraction
  uint32_t sign = (_num << 16) & 0x80000000;
  int32_t exponent = (_num >> 10) & 0x1F;
  uint32_t fraction = _num & 0x3FF;

  fraction = (fraction * 8192) & 0x7FFFFF;  // 8192 = pow(2,23) / pow(2,10)

  if(exponent == 0) {
    exponent = 0x00;
  }else if(exponent == 0x1F) {
    exponent = 0xFF;
  }else {
    exponent -= 0xF;
    if(exponent < -15 || 16 < exponent) {
      // Error 지수 범위 초과
      exponent = 0xFF;
      fraction = 0x00000000;
    }else {
      exponent += 0x7F;
    }
  }
  return (sign | (exponent << 23) | fraction);
}

 

특수한 경우의 대한 검증이 진행되지 않았기 때문에 문제가 있을 수 있습니다.

오류 발생하면 댓글 달아주시면 확인해서 수정하겠습니다.

'Programing > C' 카테고리의 다른 글

C언어에서 반올림 함수  (3) 2014.01.16
FFT C code  (1) 2014.01.16
C언어 레퍼런스  (0) 2011.11.10
Visual C++ 6.0 단축키 모음  (0) 2011.03.11