Is it possible to get the decimal value of a char? I know I can use short(char) but that would waste memory, and that is why I used char in the first place, I want only 8 bits of data, so I use char (similar to byte in C#). In my program, when I need to print it, it always shows some weird character corresponding to decimal value, I want it to show the decimal value itself. So is there a C# equivalent of char.GetNumericValue()?
Asked
Active
Viewed 516 times
0
-
Are you looking for the ascii value of the character, or do you want something like '2' to be converted to 2? – Jacob Oct 22 '20 at 06:12
-
1*How* do you print it? It is your choice whether to print it as a number or a character. – dxiv Oct 22 '20 at 06:12
-
Please show a [mre], add some more details to your problem statement and show us expected and actual output. – Lukas-T Oct 22 '20 at 06:16
-
Are you saying that `cout << short(c);` is a waste of memory or are you trying to store this as a numerical value? (It's already stored as a numerical value.) In addition, perhaps you're looking for `'1'` instead of `1`? It's hard to tell. – chris Oct 22 '20 at 06:28
-
Like all integer types, `char` holds a numeric value. By **convention**, when displayed, the value of a `char` is interpreted as a character to be displayed. If you want to display it differently (as is often the case), just pretend that it's not a `char`, i.e., by casting it: `std::cout << short(value)`. That cast doesn't affect the amount of storage that `value` uses; it just says to not do the usual interpretation, but to display the numeric value instead. Yes, `short(value)` uses more memory than `value` does, but that's only while the value is being converted for display. – Pete Becker Oct 22 '20 at 12:54
1 Answers
1
You can use one of the integer descripted in the link.
Then if the problem is only the print you can use the std::cout with this syntax
char a = 45;
cout << +a; // promotes a to a type printable as a number, regardless of type.
This works as long as the type provides a unary + operator with ordinary semantics. If you are defining a class that represents a number, to provide a unary + operator with canonical semantics, create an operator+() that simply returns *this either by value or by reference-to-const.
Further read in c++-faq print-char-or-ptr-as-number

Zig Razor
- 3,381
- 2
- 15
- 35