how to store float number (4 bytes) to a byte array
-
My application needs to store a float number into to a byte array at the specific location. i.e. at byteArray[0] to byteArray[3] will store that float number. wrote : byteArray[0] = ((byte*)&floatNumber)[0]; byteArray[1] = ((byte*)&floatNumber)[1]; byteArray[2] = ((byte*)&floatNumber)[2]; byteArray[3] = ((byte*)&floatNumber)[3]; but after write into a file and read back then cout << (float) byteArray[0] << endl; doesn't get the correct answer. How to modify above code???
-
My application needs to store a float number into to a byte array at the specific location. i.e. at byteArray[0] to byteArray[3] will store that float number. wrote : byteArray[0] = ((byte*)&floatNumber)[0]; byteArray[1] = ((byte*)&floatNumber)[1]; byteArray[2] = ((byte*)&floatNumber)[2]; byteArray[3] = ((byte*)&floatNumber)[3]; but after write into a file and read back then cout << (float) byteArray[0] << endl; doesn't get the correct answer. How to modify above code???
union FloatToCharArray {
float f;
char c[4];
};then, you use it like this :
FloatToCharArray ftc.f = 4.12;
cout << "chars are : " << ftc.c[0] << " " << ftc.c[1] << " " << ftc.c[2] << " " << ftc.c[3];
TOXCCT >>> GEII power
[VisualCalc 3.0 updated ][Flags Beginner's Guide new! ]
-
union FloatToCharArray {
float f;
char c[4];
};then, you use it like this :
FloatToCharArray ftc.f = 4.12;
cout << "chars are : " << ftc.c[0] << " " << ftc.c[1] << " " << ftc.c[2] << " " << ftc.c[3];
TOXCCT >>> GEII power
[VisualCalc 3.0 updated ][Flags Beginner's Guide new! ]
-
I stored ftc.c[0] to byteArray[0]; ftc.c[1] to byteArray[1]; ftc.c[2] to byteArray[2]; ftc.c[3] to byteArray[3]; then output: cout << (float)byteArray[0] << endl; doesn't give the correct number.
of course, it can't work, you are converting only the first char into float, not the 4 chars... use
ftc.f
(in my union) to retrieve the float...
TOXCCT >>> GEII power
[VisualCalc 3.0 updated ][Flags Beginner's Guide new! ]
-
I stored ftc.c[0] to byteArray[0]; ftc.c[1] to byteArray[1]; ftc.c[2] to byteArray[2]; ftc.c[3] to byteArray[3]; then output: cout << (float)byteArray[0] << endl; doesn't give the correct number.
This will work a bit better:
cout << *((float*)*byteArray[0]) << endl;
However, using the union described above, you could write much more clear code:union FloatWrapper { float myFloat; unsigned char myBytes[4]; }; FloatWrapper someValue; someValue.myFloat = 1.23; cout << someValue.myFloat << endl;
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac
-
I stored ftc.c[0] to byteArray[0]; ftc.c[1] to byteArray[1]; ftc.c[2] to byteArray[2]; ftc.c[3] to byteArray[3]; then output: cout << (float)byteArray[0] << endl; doesn't give the correct number.
Oh you should show the result to us. union good www.codeproject.com is a good web for our programer. I like life and I think it is living.