简体   繁体   中英

How could I cast a c++ unsigned char variable to a char variable while keeps its value

Sorry, I have gone through my code and find the place where my problem actually lies.

I hope to cast number in c++ approach. The original variable is unsigned char which I stored in a char variable a . Now I need to cast this a to double while keeping its original unsigned value. How could I do this ?

Edit:
I didn't expect my problem should be so confusing. Here is a brief example

unsigned char a;
double b;
a = 140;
char c = static_cast<char>(a);
b = static_cast<double>(c);
std::cout << b << std::endl;

This prints a result of -116 , but what I actually hopes is a double 140 . How could I do this then ?

Edit v2:

The scene is like this: I read 1024 bytes from a file with fstream. The 1024 bytes contains int numbers as well as unsigned char numbers. These unsigned char numbers I mean to cast to double types. I simplly read all of them to a std::vector<char> array, and then I need to unpack these numbers. Some part of them are to be cast to double and I met my problem here.

If my problem is brought by abuse of c++, what is the correct way to handle this task please ?

This works:

b = static_cast<double>(static_cast<unsigned char>(c));

or:

b = static_cast<unsigned char>(c);

or:

b = c < 0 ? c + 256 : c;

In c++, char max number is 127, in the assign: char a = 128; you actually get char Min value, which is -128, what means that 140 will give you a result of -116. To solve this use unsigned char , that have max value of 255. Look at the table of the types Max/Min value that in the link. https://msdn.microsoft.com/en-us/library/7fh3a000.aspx

unsigned char a = 140;
int b = a;
cout << b << endl; // 140

When you store the value of 140 in a char variable it will be out of the range of -128 to +127 for the character.

The value of 140 is converted to -119 The mechanism for this is dependent on the implementation.

The value of -119 is then converted to double and displayed as -119 in double.

What you can do is directly cast the unsigned char numbers to double. This will solve your range issues.

unsigned char a;
a = 140;
b = static_cast<double>(a);
std::cout << b << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM