Search code examples
c#stringencoding

String Encoding Program in C#


Test Case : banagalore (of type String) Expected Output : {30,20,21,92,20,80,32,31,02}

I Have converted them to ASCII using C# , now I'm not able to convert them to that sequence, kindly suggest some ideas .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("Enter The String ");
            string str = Console.ReadLine();
            byte[] b = Encoding.ASCII.GetBytes(str);
            foreach (var item in b)
            {
                Console.WriteLine(item);
            }

        }

    }
}

Solution

  • A XOR mask would be one option.

    byte[] input = Encoding.ASCII.GetBytes("bangalore");
    var known_result = new byte[] { 30, 20, 21, 92, 20, 80, 32, 31, 02 };
    var computed_mask = new byte[input.Length];
    
    for (var i = 0; i < input.Length; i++)
    {
        computed_mask[i] = (byte)(known_result[i] ^ input[i]);
    }
    
    byte[] test = Encoding.ASCII.GetBytes("bangalore");
    for (var i = 0; i < test.Length; i++)
    {
        test[i] ^= computed_mask[i];
    }
    Console.WriteLine(string.Join(",", test));