Question

I'm looking to change a vector of doubles into unsigned chars using c++. To make sure it works I wrote:

unsigned char x = 0;
double y = 4.6;
x = (unsigned char) y;
printf("%d", y);
cout << endl << "the char of 4.6 is: " << x;
getchar();

but instead of the char being equal to 4 or 5 I get a huge number like 1717986918 or a diamond symbol with cout.

I assume this is because its interpreting 4.6 as '4.6' but is there a way to save it so it just becomes an unsigned char of near equal value?

Was it helpful?

Solution

diamond symbol with cout

(unsigned char)4.6 is truncated to 4.

But when you cout a char it prints the corresponding character (eg. cout << char(65) will print A). If you want to print the value of your char then you need to cast it first to a wider integer type, eg.:

double y = 4.6;
char x = y;     // x == 4
cout << (int)x; // prints "4"
//      ^^^^^

I get a huge number like 1717986918

The problem is with your printf, you're using the wrong format specifier (%d = signed integer) compared to the argument you provide (a char). But you already figured that out, I'm just making my answer complete. ;)

Again, you probably want to cast it first:

printf("%d", (int)x);

OTHER TIPS

I assume you realize that char can only hold the integer part of the double and that too till 255 in most cases (that is why typically doubles are converted to char* to strings if you want the complete number). So what you are really looking for is to cast the integer part of the double to a char, so a lexical cast would do the trick (or itoa, stringstream functions). For ex:

#include <boost/lexical_cast.hpp>


int main() {
    unsigned char x;
    double y = 4.6;
    x = boost::lexical_cast<unsigned char>((int)y);
    printf("%f", y);
    std::cout << std::endl << "the char of 4.6 is: " << x;
}
printf("%d", y);

This is just a bug -- y is a double, and the %d format specifier is for integers.

But the main issue is a logic problem -- you're confusing numbers with their representations. When you print out character number 4, there's no reason to expect it to look like the decimal digit "4".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top