How to convert a double into an unsigned char?

user2719805 picture user2719805 · Sep 6, 2013 · Viewed 15.2k times · Source

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?

Answer

syam picture syam · Sep 6, 2013

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);