eldudorinio
September 1st, 2012, 06:18 PM
Hi,
I am unsuccessfully trying to pass a float value to an unsigned char variable in a C++ program. I have written a small C++ program to test it, but it seems that I am doing something wrong.
The unsigned char has a range from 0 to 255. So in my example I am using a float within those margins.
The other way around works just fine (unsigned char --> float).
Here is the code:
unsigned char c = 255;
float f = 128;
float i = (float) c;
unsigned char b;
b = static_cast<unsigned char> (f*255);
cout << "Casting from unsigned char to float (255) result: "<< i << endl;
cout << "Casting from float to unsigned char (128) result: "<< b << endl;
Note: I am only including <iostream>
Instead of "b = static_cast<unsigned char> (f*255)" I have also used:
b = (unsigned char) f;
b = (unsigned char) (f*255);
b = static_cast<unsigned char> (f);
All of the above give me the same output:
$ g++ test.cc
$ ./a.out
Casting from unsigned char to float (255) result: 255
Casting from float to unsigned char (128) result: �
As you can see when casting from float to unsigned char I get this unknown character.
Any ideas?
Thanks
I am unsuccessfully trying to pass a float value to an unsigned char variable in a C++ program. I have written a small C++ program to test it, but it seems that I am doing something wrong.
The unsigned char has a range from 0 to 255. So in my example I am using a float within those margins.
The other way around works just fine (unsigned char --> float).
Here is the code:
unsigned char c = 255;
float f = 128;
float i = (float) c;
unsigned char b;
b = static_cast<unsigned char> (f*255);
cout << "Casting from unsigned char to float (255) result: "<< i << endl;
cout << "Casting from float to unsigned char (128) result: "<< b << endl;
Note: I am only including <iostream>
Instead of "b = static_cast<unsigned char> (f*255)" I have also used:
b = (unsigned char) f;
b = (unsigned char) (f*255);
b = static_cast<unsigned char> (f);
All of the above give me the same output:
$ g++ test.cc
$ ./a.out
Casting from unsigned char to float (255) result: 255
Casting from float to unsigned char (128) result: �
As you can see when casting from float to unsigned char I get this unknown character.
Any ideas?
Thanks