Naresh T
Naresh T

Reputation: 319

How to read ASCII value from a character and convert it into hexadecimal formatted string

Need to read the value of character as a number and find corresponding hexadecimal value for that.

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    char c = 197;
    cout << hex << uppercase << setw(2) << setfill('0') << (short)c << endl;
}

Output:

FFC5

Expected output:

C5

Upvotes: 1

Views: 363

Answers (1)

cbuchart
cbuchart

Reputation: 11555

The problem is that when you use char c = 197 you are overflowing the char type, producing a negative number (-59). Starting there it doesn't matter what conversion you make to larger types, it will remain a negative number.

To fully understand why you must know how two's complement works.

Basically, -59 and 192 have the same binary representation: 1100 0101, depending on the data type it is interpreted in one way or another. When you print it using hexadecimal format, the binary representation (the actual value stored in memory) is the one used, producing C5.

When the char is converted into an short/unsigned short, it is converting the -59 into its short/unsigned short representation, which is 1111 1111 1100 0101 (FFC5) for both cases.

The correct way to do it would be to store the initial value (197) into a variable which data type is able to represent it (unsigned char, short, unsigned short, ...) from the very beginning.

Upvotes: 2

Related Questions