3

I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?

using System;
using System.IO;

namespace CipherDecoder
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileText = @"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";

            string cipherText = File.ReadAllText(fileText);

            string output = @"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";

            char[] cipherChars = new char[691];

            int j = 0;

            foreach (char s in cipherText)
            {
                cipherChars[j] = s;

                j++;
            }

            for(int i = 0; i < cipherChars.Length; i++)
            {
                cipherChars[i] = cipherChars[i];
            }
        }
    }
}
GiggyLapisar
  • 105
  • 3
  • 10
  • 2
    There's an implicit conversion from `char` to `int` to give you the UTF-16 code unit value as a number. For ASCII characters, that will be the same as the ASCII value. Your current code is a bit odd though - the second loop doesn't do anything, and the first would be simpler as `char[] cipherChars = cipherText.ToCharArray();` – Jon Skeet Dec 16 '15 at 14:09
  • possible duplicate http://stackoverflow.com/questions/5002909/getting-the-ascii-value-of-a-character-in-a-c-sharp-string – Syed Qasim Ahmed Dec 16 '15 at 14:12
  • Nice Explanation @JonSkeet – Syed Qasim Ahmed Dec 16 '15 at 14:13

2 Answers2

3

To get the int values into an int array you could just do this with as a LINQ select. For example:

 string fileText = @"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";

 int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
mortb
  • 9,361
  • 3
  • 26
  • 44
  • I receive the error: CS1061 C# 'string' does not contain a definition for '' and no extension method '' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?). – GiggyLapisar Dec 16 '15 at 14:55
  • 2
    Try add `using System.Linq;` to get the .Select extension method. You may also need to add a reference. Are you using VisualStudio? – mortb Dec 16 '15 at 15:05
  • You might also need to add a reference to System.Core to your project (if using VisualStudio) – mortb Dec 16 '15 at 15:06
  • That was indeed the error. All sorted and working now. Cheers – GiggyLapisar Dec 16 '15 at 18:16
1

You can,

var asciiNumbersArray = cipherText.Cast<int>().ToArray();

If you cast a char to int you get the ascii number in decimal system.

mehmet mecek
  • 2,615
  • 2
  • 21
  • 25