Mohican_4/6 C language shift operation code #FloatToInt

Notice :

The first method is not advisable

The second method is preferable: use knowledge point segment operation


#include <stdio.h>

#include <math.h>

/************************1. Use the floor and ceil functions in the c language standard library to round down or up******* ************************/
/****C language integers are encoded using original code, one's complement, and one's complement, while floating-point The type is encoded using IEEE754, so coercion is basically meaningless, because the encoding format is different ******/
/*
int FloatToInt1(float f)
{
int up = ceil(f);
int down = floor (f);
printf("Round up=%d\nRound down=%d\n", up, down);
return 0;
}
int main()
{    
FloatToInt1(11.25);
getchar();
return 0;
}*/


/************************2. Operate by shifting **************** ****************/
//Reference blog https://blog.csdn.net/huai1693838234/article/details/44804459 Using C++ to implement
//float data in the computer as IEEE754 standard storage  
//32-bit length, 1-bit real number sign bit (represented in original code), 1-bit exponent sign bit, 7-bit exponent bit (this eight bits are represented by code shift) and 23-bit data bits (complement representation)
#include<stdio .h>
#include<math.h>
union Bit
{
float val;//The value to be forced to be converted
struct H
{
//Because the machine is little endian
//Little endian simply means that high addresses store high-order low addresses and low-order structures The body member grows to the high address
//So get the
unsigned int tail:23 in the following way;//Get the last 23 bits of val, that is, the tail code
unsigned int offset: 8;//Get the middle 8 bits of val, that is, the order code+ Offset
unsigned int flag: 1;//Get the first bit of val, that is, the sign bit
}H;
};
//abs() function: find the absolute value (integer)
//exp() function: the power function of e (The x-th power value with the base e) It will be used in another method to find float to int, and this assignment will not be involved for the time being.
int FloatToInt2(float val)
{
if(abs(val) < 0.000001)//If the value is 0, return directly
{
return 0;
}
int ret;//Save the return value
Bit temp;
temp.val = val;
int offset = temp.H.offset - 127;//get the offset
ret = temp.H.tail;
ret |= 0x00800000;//fill back the discarded 1
ret = ret >> (23-offset);//The shift operation discards the digits after the decimal point
if(temp.H.flag == 1)//Negative numbers
{
ret = -ret;
}
return ret;
}
int main()
{
printf( "%d\n",FloatToInt2(-12.7));
getchar();
return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324598079&siteId=291194637