c - Binary to Float -
I wanted to produce float variables from their binary representation, and I quickly came up with the following code: P>
float bintoflot (unsigned int x) {float * f = (float *) & amp; X; Return * f; } The above function can be said as follows:
float f = bintofloat (0x3f800000); I was hoping to get some feedback on this approach: is it the best way to use pointers, or what better or more concise method?
Unfortunately, due to the use of my type, there was an inferiority; I apologize for it; For simplicity I chose to be with the underlying types but I know that it is naive, and believes that sizeof (int) == size (float) . Again, my primary question is that the use of indicators is a good way to obtain this translation from binary to a floating point?
In your code, bentoflote () in the function castings and dereferencing Invalid: float * f = (float *) & amp; X; Return * f; This will call undefined behavior at runtime
Do not convert the pointer variable into an indicator type The referenced type is more closely aligned than the referenced type. Different alignment is possible for different types of objects If a type of checking system is overridden by a clear artist or the pointer is turned into zero pointer / (zero *) And then for a different type, the alignment of an object can be changed C standard, 6.3.2.3, para 7 [ISO / IEC 98 99: 2011], says:
An object or incomplete type indicator should be changed An indicator for a different object or imperfect type. If the resulting pointer is not properly aligned for the referenced type, the behavior is undefined.
If the wrong alignment pointer is dereferenced, then the program may abort unusually. P> is an unsigned ent that has different memory alignment then float types are
typing the conversion float * f = (float *) & amp; X; is valid, but in general it is not good idea, the float type pointers should point to float type. Some systems may also provide a malignant SIGBUS when an unsigned int * indicates a float, because the float requires a more strict address alignment (float) for a multiplication of size. When you write a generic code, you are using void * in an approved way to specify an unknown type of address, but you must correctly type in Backing up the code is incorrect: unsigned int x = 10U; Unsigned int * xp = & amp; X; Zero * VP = x; Float * FP = VP; Float f = * fp; From where I have quoted, you have been given a few more examples that will help you to understand the problem.
You should also read this reply:
Edit: I think you can do something like:
# include & Lt; Stdio h & gt; Float bintoflot (unsigned int x) {union} (unsigned int x float f;) temp; temp.x = x; return to temp.f;} int main () {float f = bintofloat (0x4236AE14U); printf (" nf =% f ", f); Printf (" \ nf =% f \ n ", bintoflot (0x4287F0A4U); return 0;} Use this as: / p>
$ gcc-west-payment binaryfolat.Taxspanner @: ~ $ ./a.outf = 45.669998f = < / Li> / html>
Comments
Post a Comment