I'm trying to convert String to ASCII
code, so i use this function :
public List<string> PrimaryCode(string OrginalStr)
{
List<string> lstResult = new List<string>();
int lenOrginal = OrginalStr.Length;
string subOrginalStr;
byte[] AsciisubOrginalStr;
int AC;
for (int i = 0; i < lenOrginal; i++)
{
subOrginalStr = OrginalStr.Substring(i, 1);
AsciisubOrginalStr = Encoding.ASCII.GetBytes(subOrginalStr);
if (AsciisubOrginalStr[0] > 100)
{
AC = Convert.ToInt32(AsciisubOrginalStr[0]);
lstResult.Add((AC ).ToString());
}
else
{
AC = Convert.ToInt32(AsciisubOrginalStr[0]);
lstResult.Add((AC).ToString());
}
}
return lstResult;
}
The other part of my project i need to convert the ASCII
code to original text as you can see i use this function :
public List<string> PrimaryCodeRev(List<string> CodedStr)
{
string res = "";
foreach (string s in CodedStr)
{
res = res+s;
}
List<string> lstResult = new List<string>();
int lenOrginal = res.Length;
string subOrginalStr;
byte[] AsciisubOrginalStr;
int AC;
for (int i = 0; i < lenOrginal; i++)
{
subOrginalStr = res.Substring(i, 1);
AsciisubOrginalStr = Encoding.ASCII.GetBytes(subOrginalStr);
if (AsciisubOrginalStr[0] < 100)
{
AC = Convert.ToInt32(AsciisubOrginalStr[0]);
lstResult.Add((AC).ToString());
}
else
{
AC = Convert.ToInt32(AsciisubOrginalStr[0]);
lstResult.Add((AC).ToString());
}
}
return lstResult;
}
The string input hello
convert to ascii result :
Convert ascii to main text :
But it doesn't work and it doesn't return the main text. Why ?
You seem to be making it too complicated...
If your input string only ever contains ASCII characters (which must be a requirement), then you can encode it as follows:
public static IEnumerable<string> ToDecimalAscii(string input)
{
return input.Select(c => ((int)c).ToString());
}
You can convert it back to a string like so:
public static string FromDecimalAscii(IEnumerable<string> input)
{
return new string(input.Select(s => (char)int.Parse(s)).ToArray());
}
Putting it together into a compilable console program:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string original = "hello";
var encoded = ToDecimalAscii(original);
Console.WriteLine("Encoded:");
Console.WriteLine(string.Join("\n", encoded));
Console.WriteLine("\nDecoded: " + FromDecimalAscii(encoded));
}
public static IEnumerable<string> ToDecimalAscii(string input)
{
return input.Select(c => ((int)c).ToString());
}
public static string FromDecimalAscii(IEnumerable<string> input)
{
return new string(input.Select(s => (char)int.Parse(s)).ToArray());
}
}
}
Let me reiterate: This will ONLY work if your input string is guaranteed to contain only characters that are in the ASCII set.
This does not really answer the question of why you want to do this. If you are trying to encode something, you might be better using some sort of encrypting method which outputs an array of bytes, and converting that array to base 64.