Newbie: Some help with ASCII

This is a discussion on Newbie: Some help with ASCII within the C++ Programming forums, part of the General Programming Boards category; Well this is my first post on the forum. Been browsing the site for some days but i need some ...

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    19

    Newbie: Some help with ASCII

    Well this is my first post on the forum. Been browsing the site for some days but i need some quick help so figured, why not go here?

    Well im pretty new to this whole programming thing, although ive made a few programs. My pride and joy is a program to handle prime numbers. You set up an interval of your choosing and then the program will find all the prime numbers in the interval. You can input a single number within the interval and the program will then find the neares prime number above and below. You can output a complete list of the primes in the interval and save them in a file... and i think also some other stuff...

    The point is that i know a little but i dont realy know anything about ASCII. Not true, i know what it is but i dont know how to work with it. Im trying to make a simple encryption and decryption program where the ASCII values are changed. I.e. five is added so that "a" (97) becomes "f" (102) but i have no idea on how do actualy do this. I hope some of you guys in here can help me?

  2. #2
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    ASCII pairs each character with an integer, like 97 for 'a'. Because of this, you can cast back and forth between chars and ints (Just be careful you don't lose important information). You can therefore add integers to chars and chars to chars.
    Code:
    	string plaintext = "theeaglefliesatmidnight";
    	string ciphertext;
    	int n = plaintext.length();
    	int offset = 3;
    	for(int i =0; i < n; ++i)
    	{
    	  ciphertext += ( ( (plaintext[i] - 'a') + offset) % 26) + 'a';
    	}
    	cout << ciphertext << endl;
    This code implements a Caesar cipher.

    plaintext[i] is the ith letter in that string.
    I subtract 'a' so that the lowercase alphabet is shifted to [0-25].
    I add the offset. This is the part that actually does the encryption. 'a' becomes 'd', etc.
    I modulo 26 so that 'z' will become 'c', etc. This part is important.
    And finally, I add 'a' back so that the lowercase alphabet displays its proper ASCII values.
    Last edited by joshdick; 04-27-2005 at 10:49 AM.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,447
    Code:
    char letter = 'a';
    letter += 5;
    cout << letter;
    Which is OK while everything remains printable, but usable encryption needs to
    a) deal with binary data
    b) is likely to output binary data
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Quote Originally Posted by Salem
    Which is OK while everything remains printable, but usable encryption needs to
    a) deal with binary data
    b) is likely to output binary data
    Tell that to Caesar, everyone in WWII, and everyone living in between

    SilverAdder, after you understand the Caesar cipher, I suggest you implement the Vigenere cipher and after that some digraph ciphers.

    I wouldn't send any credit card numbers using the Playfair cipher, but let's face it: Classical Cryptography is much more fun.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  5. #5
    Registered User
    Join Date
    Apr 2005
    Posts
    19
    ... All i heard was ASCII and then... white noise. No seriously im so lost. The only reply i realy understood was Salems. So thanks dude I didnt know you could just do it like that. But the wouldnt work if there were more letters would it? I dont suppose i can just set up an array and then add five to the entire array...

  6. #6
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Because strings resize themselves nicely, that code will work on a plaintext message of any length. It doesn't, however, deal with any characters other than lowercase letters.

    A std::string is not an array.
    If you do something like
    an_array+5;
    that will not do what you think. You'll learn more about that when you learn pointers. For now, I suggest using std::string as they're much easier to use.

    In order to do something to every member of a string or array, you should loop over every element in them. For example,
    Code:
    string s = "SilverAdder";
    int n = s.length();
    for(int i = 0; i < n; ++i)
      cout << s[i] << endl;
    Would output:
    S
    i
    l
    v
    e
    r
    A
    d
    d
    e
    r
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  7. #7
    Registered User
    Join Date
    Apr 2005
    Posts
    19
    Im with you so far. I en up with this:

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    int n;
    int i;
    //int e;
    
    int main()
    {
    string s = "SilverAdder";
    n = s.length();
    
    for(i = 0; i < n; i++) 
    {
        cout << s[i] << endl;
    }
    getch();
    return 0;
    And it works just like you said. But how do i change the ASCII values for the text in the loop?

  8. #8
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Depends on what you want to change them to, but you can more or less treat them like integers using +, -, and %. For the Caesar cipher, add 3 to each char and modulo 26.

    Don't use global variables. Those declarations should go inside of main().
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  9. #9
    Registered User
    Join Date
    Apr 2005
    Posts
    19
    Alright thanks. Ill experiment a little with this. And thanks for the pointer on globals. Ill remember that Ill give a shout here once i get stuck again

  10. #10
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Glad I could help.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  11. #11
    Registered User
    Join Date
    Apr 2005
    Posts
    19
    Well, seems i finaly made what i wanted to! Not the most comprehencive program but still... its more than ive ever made before Its probably not the best method but still it works... I descided to typecast the loop and add 5. Lots of parentheses but it gets the job done

    Code:
     
    #include <cstdlib>
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    int main()
    {
    string tekst = "SilverAdder";
    int n = tekst.length();
    
    for(int i = 0; i < n; i++) 
    {
        cout << tekst[i] << endl;
    }
    getch();
    
    cout << endl;
    
    for (int i = 0; i < n; i++)
    {
        cout << (char)(((int)tekst[i])+5) << endl; 
    }
    getch();
    
    return 0;
    }

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    1) Since you are apparently trying to learn C++, get rid of

    <conio.h>, <cstdlib> and getch()

    See here:

    http://faq.cprogramming.com/cgi-bin/...&id=1043284385


    2) You need to include <string> for string types.

    3) C++ casts look like this:

    static_cast<char>(88)

    In addition, if you add an integer to a char like this:

    tekst[i] + 5

    the compiler can't add two differing types, so it automatically converts tekst[i] from char to int. Then, the compiler has two int's, so it adds 5 creating an int result. So, you can do this:

    static_cast<char>(tekst[i] + 5);

    The result from the addition is an int, which is then cast to a char.
    Last edited by 7stud; 04-28-2005 at 02:10 AM.

  13. #13
    Registered User
    Join Date
    Apr 2005
    Posts
    19
    Alright i tried getting rid of getch() but i couldnt get cin.get to work. The program never paused, it just ran through it all and closed. I left the code in there if somecan give me a hand, otherwise im just gonna use getch.

    Now i also tried to change it so that i can encrypt af user input and it sort of works. The problem is that if the input cintains a space, the encryption screws up and not all the text gets encrypted, or something like that. At any rate, the decrypted tekst isnt identical to the original input.

    I included af copy of the first code at the end of the program, but without the input being controlled by the user. As much for my own sake as anything else... I hope you guys can help me with this...

    Code:
     
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    char key[13]="ABCDEFGHIJKL";
    
    int main()
    {
        char input[13];
        cin >> input;
    
        for(int x=0; x<12; x++)
        {
            input[x] = input[x]^key[x];
            cout << input[x];
        }
        cout << endl;
      
        for (int x=0; x<12; x++)
        {
            input[x] = input[x]^key[x];
            cout << input[x];
        }
      cout << endl << endl;
      
    /*  cin.ignore();
      cout << "Press Enter" << endl;
      cout << endl;
      cin.get(); */
      getch();
        
        char input2[13]="Silver Adder";
        cout << input2 << endl;
        for (int x=0; x<12; x++)
        {
            input2[x] = input2[x]^key[x];
            cout << input2[x];
        }
        cout << endl;
      
        for (int x=0; x<12; x++)
        {
            input2[x] = input2[x]^key[x];
            cout << input2[x];
        }
    /*  cout << endl << endl;
      cout << "Press Enter" << endl;
      cout << endl;
      cin.get(); */
      getch();
      return(0);
    }

  14. #14
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    FAQ > How do I... (Level 1) > Stop my Windows Console from disappearing everytime I run my program?
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    I suggest using std::strings rather than arrays of chars.

    Most people don't bother encrypting spaces. Instead, they just smush all the letters together and then encrypt or decrypt. I suggest writing a function to remove the whitespace from a string. The function isspace() in <cctype> will help with that.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  15. #15
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    The program never paused, it just ran through it all and closed. I left the code in there if somecan give me a hand, otherwise im just gonna use getch.
    cin.get() will only pause if there is no more input to read. The reason it pauses is because it needs input.

    When you enter input in the console, it doesn't matter whether a previous read attempt only read part of the input that was entered--the rest of the input still remains and is waiting to be read. If cin.get() is executed when there is still input available, it does not have to wait for user input, and so it reads in a char and your program ends.

    The problem is that if the input cintains a space, the encryption screws up and not all the text gets encrypted, or something like that.
    This line:
    Code:
    cin >> input;
    causes input to stop being read in when a space is encountered--that is the way ">>" is defined to work. To read in a whole line of data--spaces and all--you need to use getline():
    Code:
    char input[13];
    cin.getline(input, 13);
    That will read in a maximum of 12 characters from the console, and tack on a '\0' character in the last spot in the array.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 03-24-2006, 10:26 AM
  2. Office access in C/C++ NOT VC++!! :)
    By skawky in forum C++ Programming
    Replies: 1
    Last Post: 05-26-2005, 01:43 PM
  3. TEXT FILE TO ASCII - newbie
    By skwattakamp in forum C Programming
    Replies: 18
    Last Post: 12-23-2004, 09:01 AM
  4. ascii values for keys
    By acid45 in forum C Programming
    Replies: 2
    Last Post: 05-12-2003, 07:13 AM
  5. Checking ascii values of char input
    By yank in forum C Programming
    Replies: 2
    Last Post: 04-29-2003, 07:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21