How to convert float to int

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.