Created
June 12, 2018 12:34
-
-
Save tuliopaim/d3a2685bcd2dffb6320e501d2518856e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #define makefloat(s,e,f) ((s & 1)<<31 | (((e) & 0xff) << 23) | ((f) & 0x7fffff)) | |
| #define getsig(x) ((x)>>31 & 1) | |
| #define getexp(x) ((x)>>23 & 0xff) | |
| #define getfrac(x) ((x) & 0x7fffff) | |
| typedef union { | |
| float f; | |
| unsigned int i; | |
| } U; | |
| //ex1 | |
| float float2(float f){ | |
| U u; | |
| u.f = f; | |
| u.i = makefloat(getsig(u.i),getexp(u.i)+1,getfrac(u.i)); | |
| return u.f; | |
| } | |
| //ex2 | |
| float int2float(int i){ | |
| if(i == 0) return 0.0; | |
| //descobrir exponencial | |
| int e = 0; | |
| i = (i < 0) ? -i : i; | |
| unsigned int temp =i; | |
| while(temp != 1){ | |
| //printf("bit: %d\n", temp & 1); | |
| temp = temp >> 1; | |
| e++; | |
| } | |
| int f = i; | |
| //fazer a mascara | |
| int mask = 0; | |
| for(int j = 0; j < e ;j++){ | |
| mask = mask << 1; | |
| mask = mask | 1; | |
| //printf("bit: %d (%d)\n", mask & 1,j ); | |
| }//printf("\n\n"); | |
| f = f & mask; | |
| f = f << (23-e); | |
| printf("%x %x\n", f, mask); | |
| //exp | |
| int exp = e + 127; | |
| //signal | |
| int signal = (i < 0); | |
| U u; | |
| u.i = makefloat(signal, exp, f); | |
| //imprimir | |
| /* | |
| for(int j = 0; j < sizeof(int)*8; j++){ | |
| if(j==1 || j==9) printf("------\n"); | |
| printf("bit(%d): %d \n",j , u.i & 1); | |
| u.i <<= 1; | |
| }*/ | |
| return u.f; | |
| } | |
| int main(){ | |
| //printf("%f\n",float2(5.0)); | |
| printf("\n%.1f\n",int2float(-1521)); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment