Character to ASCII

How to show ASCII does of any character in C++. I want to make a character to ASCII converter.
Simply cast it to an integer.

1
2
3
char ch = 'a';
int ascii = (int)ch;
int ascii2 = static_cast<int>( ch );


*edit - forgot the '/' in code

int toAscii( const char ch ){ return static_cast<int>( ch ); }
Last edited on
I tried it but it's not working
What's not working? (Be more specific.)

What do you have so far?
Umm, honestly, I didn't start because I'm not getting what to do. Basically my idea is to make a text encrypter. So I want the text to convert into a code and then again convert into normal text.
So first I thought that I'll convert into ASCII and then reconvert it back into text.
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
#include <string>
#include <iostream>
#include <iomanip>

unsigned to_unsigned(char ch)
{
    return static_cast<unsigned>(static_cast<unsigned char>(ch));
}

int main()
{
    std::cout << "Enter a string: ";

    std::string line;
    std::getline(std::cin, line);

    for (std::size_t pos = 0; pos < line.size(); ++pos)
    {
        std::cout << std::setfill(' ');
        std::cout << std::setw(2) << line[pos];

        unsigned ascii = to_unsigned(line[pos]);

        std::cout << " = " << std::setw(3) << std::dec << ascii;
        std::cout << " = 0x" << std::setw(2) << std::hex << std::setfill('0') << ascii;
        std::cout << '\n';
    }
}


http://ideone.com/c5HA7k


If you are trying to make a cipher you can modify the characters directly.

1
2
3
std::string str = "Hello World!";
for( int i = 0; str[i]; ++i )
    ++str[i];


of course this is a very basic one and does not check if they are letters and loop back when they go past 'z' you can however modify for that to make a basic caesar cipher.

[edit]Caesar cipher or just a normal shift cipher

http://en.wikipedia.org/wiki/Caesar_cipher
http://www.math.cornell.edu/~mec/Summer2008/lundell/lecture1.html

https://www.khanacademy.org/math/applied-math/cryptography/ciphers/a/ciphers-vs-codes --- Very interesting site and would recommend.
Last edited on
wow thanks!
Topic archived. No new replies allowed.