float to int 2진수로 해보기

Seungsoo Lee·2022년 11월 8일
0

cs

목록 보기
2/2

앞서서 123.45라는 친구가 부동소숫점(Float)으로, 0|1000010 1|1110110 11101110 01100110 으로 표현이 되었다.

순서

여기서 Bits는 부동소숫점을 말한다.

  • Fraction 구하기
    Bits and 0x7FFFFF
    fraction은 23자리 부분이다. 23자리 부분만 남긴다.
    • 계산
      01000010 11110110 11101110 01100110
      &
      00000000 01111111 11111111 11111111
      =
      00000000 01110110 11101110 01100110
  • Exponent 구하기
    ((bits >> 23) and 0xFF) - 127
    Exponent는 구한방법의 반대로 실행한다.
    • 계산
      01000010 11110110 11101110 01100110
  • Fraction에다 1.0 추가
    (0x8000000 | fraction)
    • 계산
      00000000 10000000 00000000 00000000
      |
      00000000 01110110 11101110 01100110
      =
      00000000 11110110 11101110 01100110
  • int 부분만 남기고 다 shift
    00000000 11110110 11101110 01100110 >> (23 - expose)
    =
    00000000 00000000 00000000 11110110
    • Fixed point로 만들기
      • 00000000 11110110 11101110 01100110 >> (15 - expose)
        =
        00000000 00000000 11110110 00000000

code

void floatToInt(float num)
{

	std::cout << num << std::endl;

	// float num to bit
	std::bitset<sizeof(float)*CHAR_BIT> fraction(*reinterpret_cast<unsigned long*>(&num));

	std::cout << "num bit" << std::endl;
	std::cout << fraction << std::endl;

	fraction &= 0x7FFFFF; // get fraction only

	std::cout << "fraction only" << std::endl;
	std::cout << fraction << std::endl;


	// calculate exponent ((bits >> 23) & 0xFF) - 127
	std::bitset<sizeof(float)*CHAR_BIT> exponent(*reinterpret_cast<unsigned long*>(&num)); // expo
	exponent >>= 23; // expo
	exponent &= 0xFF; // expo

	std::cout << "expo before -127" << std::endl;
	std::cout << exponent << std::endl;
	std::bitset<sizeof(float)*CHAR_BIT> y(127);
	// -127
	while (y != 0)
	{
		std::bitset<sizeof(float)*CHAR_BIT> borrow((~exponent) & y);
		exponent = exponent ^ y;
		y = borrow << 1;
	}
	std::cout << "expo" << std::endl;
	std::cout << exponent << std::endl;



	// move bits to int ((0x800000 | fraction) >> (23 - exponent))
	std::bitset<sizeof(float)*CHAR_BIT> m_80(0x800000); 
	std::bitset<sizeof(float)*CHAR_BIT> integer(fraction | m_80); // integer
	// add 1
	std::cout << "add 1" << std::endl;
	std::cout << integer << std::endl;	// integer

	std::bitset<sizeof(float)*CHAR_BIT> x(23 - 8); // fixed point
	// std::bitset<sizeof(float)*CHAR_BIT> x(23); // integer
	while (exponent != 0)
	{
		std::bitset<sizeof(float)*CHAR_BIT> borrow((~x) & exponent); // integer
		x = x ^ exponent;
		exponent = borrow << 1;
	}
	std::bitset<sizeof(float)*CHAR_BIT> uoo(integer >> x.to_ulong()); // integer
	std::cout << uoo << std::endl;
}

0개의 댓글