how do I convert float to the unsigned char * array
Depends on what you want to achieve by such conversion.
- If you want to convert it into a textual representation, then you can use a string stream.
- If you want to convert it to a sequence of bytes, then you can use
std::memcpy
to copy those bytes onto an array of unsigned char
(you might alternatively use std::byte
):
Example:
unsigned char buf[sizeof preCent];
std::memcpy(buf, &preCent, sizeof preCent);
... and print it
- If you want the textual representation, simply insert the string into the standard output (
std::cout
)
- If you want to see the byte sequence, you cannot let the stream interpret the byte array as a character encoded string, since binary data is not meaningful in that representation. You can iterate the bytes and show the numeric value of each byte:
Example:
for(unsigned char c : buf)
std::cout << std::hex << (int)c;
Note the conversion to a non-character integer type to prevent the stream from interpreting the byte as an encoded character.
How [to] print the real float value
I want to print the float value after I convert it to unsigned char *
Simply convert the byte array back into a float using std::memcpy
in reverse direction:
float converted_back;
std::memcpy(&converted_back, buf, sizeof converted_back);
std::cout << converted_back;
printf(" %lf ", buf); // prints -0.000000
The %lf
requires that the argument is of type double (or float which will be converted into double). However, you passed buf
which is of type unsigned char[4]
. The behaviour of your program is undefined because you violate this precondition.
printf(" %s ", buf); // print bytes
%s
specifier requires that the argument is a null terminated string. Your character array is not null terminated. The behaviour of your program is undefined because you violate this precondition. Besides, the data of your array is meaningless in character encoded representation.
std::cout << buf << std::endl; // print bytes
Character streams have the same requirements for inserted pointers as %s
printf specifier does. The behaviour is undefined.
unsigned char buf[4];
...
return buf;
You return a pointer to a local array. The array is destroyed at the end of the function, and the returned pointer is dangling.
std::cout << readRequestArray << std::endl;
You insert a dangling pointer into a character stream. The behaviour of your program is undefined. Even if it wasn't dangling, the array it used to point to (the local buf
) is still not a null terminated string.