Recently suddenly want to know how to implement the floating-point in the compiler, but looked at a lot of information incredibly there is no record on this aspect, so I decided to implement a simple float to int as an example double to int similar
Before you do a strong turn, you first need to know how the floating-point number is stored in memory, you can refer to my previous article on how floating-point numbers in memory are stored in C + +
with the above foundation, then we directly on the code. I'll make the comments in the code, the code is simple, basically easy to understand
#include <iostream> #include <math.h>using namespace std;union bit{float val;//The value that will be strongly transferred struct h{// Why this acquisition is due to my machine is the small end of the reason//small end is simply the high address of the low address of the lower-level structure member is to the high address growth//So the following way to get unsigned int tail:23;//get Val The last 23 bits of the tail code unsigned int offset:8;//Gets the middle 8-bit code + offset of val unsigned int flag:1;//gets the first bit of Val, the sign bit}h;}; int Floattoint (float val) {if (ABS (val) < 0.000001)//If 0 value is returned directly {return 0;} int ret;//Save the return value bit temp;temp.val = val;int offset = temp. h.offset-127;//Get offset//cout<<offset<<endl;ret = temp. H.tail;ret |= 0x00800000;//will discard 1 fill back ret = ret >> (23-offset);//shift operation discards the decimal number if (temp. H.flag = = 1)//negative number {ret =-ret;} return ret;} int main () {float val = 0.0;cout<<floattoint (val) <<endl;val = -16.29;cout<<floattoint (val) << Endl;val = -0.183;cout<<floattoint (val) <<endl;val = 12.25;cout<<floattoint (val) <<endl; return 0;}
How to convert float to int