Floating Point Converter

hee0·2024년 8월 12일

Quantization

목록 보기
1/5

https://www.h-schmidt.net/FloatConverter/IEEE754.html

Floating Point Converter 를 구현해보았다.

#include <bits/stdc++.h>
using namespace std;

/// hyper parameter //
int n_bits = 32;
int exponent_bit = 8;
//////////////////////

int sign_bit = 1;
int fraction_bit = n_bits - exponent_bit - sign_bit;

int exponent_start = sign_bit;
int exponent_end = exponent_start + exponent_bit;
int fraction_start = exponent_end;
int fraction_end = fraction_start + fraction_bit;

string Decimal2FloatingPoint(float n){
	string sign = "";
	if(n >= 0) sign += '0';
	else {
		sign += '1';
		n *= -1;
	}
	float decimal = n;
	int bias = (1<<(exponent_bit-1))-1; // bias

	int int_exp = 0;
	while(decimal > 2){
		decimal /= 2;
		int_exp ++;
	}
	int_exp += bias;

	string exponent = "";
	for(int i=0; i<exponent_bit; i++){
		if(int_exp >0 && int_exp % 2){
			exponent = '1' + exponent;
		}else{
			exponent = '0' + exponent;
		}
		int_exp /= 2;
	}

	string fraction = "";
	for(int i=0; i<fraction_bit; i++){
		if (decimal >= 1) decimal -= 1.0;
		decimal *= 2;
		if(decimal >= 1) {
			fraction += '1';
		}else{
			fraction += '0';
		}
	}
	cout <<  sign + exponent + fraction << "\n";
	return sign + exponent + fraction;
}
float FloatingPoint2Decimal(string s){
	int sign = s[0] == '1' ? -1: 1;
	int bias = (1<<(exponent_bit-1))-1; // bias (2^(n-1)-1)
	int exp = 0;
	for(int i=exponent_start; i<exponent_end; i++){
		exp <<= 1;
		exp |= (s[i] - '0');
	}
	exp -= bias; 
	float integer = 1;
	float fraction = 0;
	for(int i=fraction_start; i<fraction_end | 0<=exp; i++, exp--){
		if(exp>0){
			integer *= 2;
			integer += (s[i] - '0');
		}else{
			fraction *= 2;
			fraction += (s[i] - '0');
		}
	}
	for(int i=exp; i<0; i++){
		fraction /= 2;
	}
	printf("%.10f\n", ((float) integer + fraction ) * sign);
	return ((float) integer + fraction ) * sign;
}

int main(){

	FloatingPoint2Decimal(Decimal2FloatingPoint(10.24532143));

	return 0;
}

//입력
10.24532143

//출력
01000001001000111110110011010110
10.2453212738

profile
개발 0부

0개의 댓글