Prasadika
Prasadika

Reputation: 917

C# - Decode strings encoded with ISO-8859-1

My purpose in writing the following program was to encode a set of strings using ISO-8859-1. I am now in need of getting it decoded. Consequently, I should receive "100, 200, 300, Test String One, Test String Two, Test String Three" back.

class Program
{
    private const int ENC_INT_SEED = 2136;
    private const int ENC_CHAR_SEED = 43;
    private const int ENC_INT_VAL = 3765;
    private const int ENC_CHAR_VAL = 139;
    private const int ENC_DUMMY_COUNT = 17;

    static void Main(string[] args)
    {
        string fileName = @"C:\Users\User\Documents\Test.DTA";

        FileStream fs = new FileStream(fileName, FileMode.Create, 
                    FileAccess.Write);
        BinaryWriter bw = new BinaryWriter(fs);

        int dummy = 0;
        for (int i = 0; i < ENC_DUMMY_COUNT; i++)
        {
            bw.Write(dummy);
        }

        int int_seed = ENC_INT_SEED;
        char char_seed = (char)ENC_CHAR_SEED;            

        for (int i = 0; i < 30; i++)
        {

            SaveInt(100, bw, ref int_seed);
            SaveInt(200, bw, ref int_seed);
            SaveInt(300, bw, ref int_seed);

            SaveString("Test String One", bw, ref int_seed, ref char_seed);
            SaveString("Test String Two", bw, ref int_seed, ref char_seed);
            SaveString("Test String Three", bw, ref int_seed, ref 
            char_seed);

        }

        bw.Close();
        fs.Close();

        Console.ReadLine();
    }
    private static void SaveString(string str, BinaryWriter bw, ref int 
                     int_seed, ref char char_seed)
    {
        int len = str.Length;

        Encoding encLatin_1 = Encoding.GetEncoding("ISO-8859-1");
        byte[] c = encLatin_1.GetBytes(str);

        int_seed = int_seed + ENC_INT_VAL + len;
        bw.Write(int_seed);

        for (int i = 0; i < len; i++)
        {
            int temp = char_seed + ENC_CHAR_VAL + c[i];
            char_seed = (char)temp;
            c[i] = (byte)char_seed;
        }
        bw.Write(c, 0, len);
    }
    private static void SaveInt(int i, BinaryWriter bw, ref int seed)
    {
        seed = seed + ENC_INT_VAL + i;
        bw.Write(seed);
    }
}

I need some help with decoding as I am no expert in this matter and just managed to do the encoding. Please help

Upvotes: 0

Views: 383

Answers (1)

Jesse de Wit
Jesse de Wit

Reputation: 4177

I wouldn't bother writing your own method for this, since C# has built-in support for encodings:

byte[] inputBytes = // get your bytes

// There is built-in support for encodings in C#
string result = Encoding.GetEncoding("ISO-8859-1").GetString(inputBytes);

Upvotes: 2

Related Questions