앞서서 123.45라는 친구가 부동소숫점(Float)으로, 0|1000010 1|1110110 11101110 01100110
으로 표현이 되었다.
여기서 Bits는 부동소숫점을 말한다.
Bits and 0x7FFFFF
01000010 11110110 11101110 01100110
00000000 01111111 11111111 11111111
00000000 01110110 11101110 01100110
((bits >> 23) and 0xFF) - 127
01000010 11110110 11101110 01100110
(0x8000000 | fraction)
00000000 10000000 00000000 00000000
00000000 01110110 11101110 01100110
00000000 11110110 11101110 01100110
00000000 11110110 11101110 01100110
>> (23 - expose)00000000 00000000 00000000 11110110
00000000 11110110 11101110 01100110
>> (15 - expose)00000000 00000000 11110110 00000000
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;
}