struct - Creating own float structure in C++ -
yet lectures in c++ @ university began yet got first problems. our task implement self made structure in c++ floating points via ieee 754 standard:
create data structure allows store float, read raw byte representation , internal representation s, e , m. use combination of union , bit-field-struct. write program float number assigned float part of structure , raw , s/e/m representation printed. use hexadecimal output raw , m.
what had far following:
#include <stdio.h> #include <math.h> union { struct kfloat { //using bit fields our self made float. s sign, e exponent, m mantissa //it should unsigned because use 0 , 1 unsigned int s : 1, e : 8, m : 23; }; //one bit wasted our '.' char internal[33]; }; float calculaterealfloat(kfloat kfloat) { if(kfloat.s == 0) { return (1.0+kfloat.m)*pow(2.0, (kfloat.e-127.0)); } else if (kfloat.s == 1) { return (-1.0)*((1.0+kfloat.m)*pow(2.0, (kfloat.e-127.0))); } //error case when s bigger 1 return 0.0; } int main(void) { kfloat kf_pos = {0, 128, 1.5707963705062866};//this should pi (rounded) aka 3.1415927 kfloat kf_neg = {1, 128, 1.5707963705062866};//pi negative float f_pos = calculaterealfloat(kf_pos); float f_neg = calculaterealfloat(kf_neg); printf("the positive float %f or ",f_pos); printf("%e\n", f_pos); printf("the negative float %f or ",f_neg); printf("%e", f_neg); return 0; }
the first error code mantissa absolutely wrong have no idea how fix this.
please reread task:
create data structure allows store float, read raw byte representation , internal representation s, e , m.
this not mean should store string
i following way:
union myfloat { unsigned char rawbytedatarep[4]; unsigned int rawdatarep; float floatrep; struct{ // not checked part copied unsigned s : 1; unsigned e : 8; unsigned m : 23; } componentesrep; }
but careful! besides fact union-conversion pattern used, c-standard states result undefined behaviour if read unionmember 1 written.
edit: added uint32 rep
void testmyfloat() { myfloat mf; mf.floatrep = 3.14; printf("the float %f assembled sign %i magnitude 0x%08x , exponent %i , looks in memory 0x%08x.\n", mf.floatrep, (int)mf.componentesrep.s, (unsigned int)mf.componentesrep.m, (int)mf.componentesrep.e, mf.componentesrep.rawdatarep); }
Comments
Post a Comment