-
Notifications
You must be signed in to change notification settings - Fork 0
/
29_demote.c
74 lines (61 loc) · 1.51 KB
/
29_demote.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/***************************************************************************************
DOCUMENTATION:
NAME : V.KARTHIEKEYAN
DATE : 11.08.2021
DESCRIPTION : WAP to demote the type of given float number to integer using bitwise
operators and bitfields.
OUTPUT :./a.out
ENTER A FLOAT VALUE: 12.34
DEMOTED VALUE: 12.000000
DO YOU WANT TO CONTINUE(y/Y) :y
ENTER A FLOAT VALUE: -12.34
DEMOTED VALUE: -12.000000
DO YOU WANT TO CONTINUE(y/Y) :n
****************************************************************************************/
#include<stdio.h>
/* union where float data is shared with bitfields*/
union Float
{
float f;
struct
{
unsigned int mantissa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
};
}var;
void demote_to_int(union Float *);
int main()
{
char choice;
do
{
printf("\nENTER A FLOAT VALUE: ");
scanf("%f",&var.f);
printf("exponent=%u\n",var.exponent);
demote_to_int(&var);
printf("DEMOTED VALUE: %f\n",var.f);
printf("DO YOU WANT TO CONTINUE(y/Y) :");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
/*function to demote the value of float to int*/
void demote_to_int(union Float *var)
{
//standard bias number = 127
int exponent = var -> exponent - 127 ;
if( exponent <= 0 && var -> f > -1.0f && var -> f < 1.0f)
{
var -> f = 0;
}
else
{
int mantissa = (var -> mantissa) >> (23 - exponent);
exponent = 1 << exponent;
if (var -> sign == 1)
var -> f = -(exponent | mantissa);
else
var -> f = exponent | mantissa;
}
}