How to get ANSI value for char in C++

I have a file encoded in ANSI.
I need Hex code for the char.
For Example
char: ^
ANSI code is 136 or 88(In Hex).
Using stream allows you to output a value as hex. See:

http://www.cplusplus.com/reference/ios/hex/

Note that you cannot use the type char for this since the stream handles char and unsigned char specifically. So you may cast it like so:

1
2
  char ch = 136;
  std::cout << std::hex << static_cast<int>(static_cast<unsigned char>(ch)) << '\n';


Note that you need to cast it as unsigned char first. Otherwise it would be interpreted as a negative value.
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main()
{
   unsigned char c = 136;     // not displayable on many terminals
   cout << hex << int( c ) << '\n';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>
#include <locale>
#include <iomanip>
#include <cctype>

int main()
{
    const char file_name[] = __FILE__ ;

    if( std::ifstream file{ file_name, std::ios::binary } ) // if the file is opened for input (in binary mode)
    {
        // set the locale of the file stream (and stdout) to one that uses a suitable ANSI character encoding (this example uses UTF8)
        file.imbue( std::locale( "en_US.UTF8" ) ) ; // note: the locale name string is implementation dependant
        std::cout.imbue( std::locale( "en_US.UTF8" ) ) ; // note: the locale name is string implementation dependant
        
        std::cout << std::showbase ;
        char ch ;
        while( file.get(ch) ) // for each char (including white space chars) read from the file
        {
            const unsigned int v = ch ;
            
            if( std::isprint( ch, std::cout.getloc() ) ) std::cout << "'" << ch << "'  " ; // print the literal char if it is printable
            else std::cout << "     " ;
            
            // print its integer value in decimal and hexadecimal 
            std::cout << std::setw(4) << std::dec << v << std::setw(5) << std::hex << v  << '\n' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/f5272238ce144637
Last edited on
C++20 adds a nice feature with <format>'s formatting library, similar to C's printf(), that can be used to display a number in binary, octal, hex or decimal notation:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <format>

int main()
{
   unsigned char c { static_cast<unsigned char>(136) };

   std::cout << std::format("Default: {0}, decimal: {0:d}, hex.: {0:#x}, octal: {0:#o}, binary: {0:#b}\n", c);
}
Default: 136, decimal: 136, hex.: 0x88, octal: 0210, binary: 0b10001000

https://en.cppreference.com/w/cpp/utility/format
Topic archived. No new replies allowed.