Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

Habbo Base64 [D programming language]

Software Engineer
Loyal Member
Joined
Feb 19, 2008
Messages
1,055
Reaction score
492
So I was browsing 4chan, and somehow this code ended up in my text editor.

Code:
import std.stdio;
import std.math;

///	Summary:
///	Provides Base64 encoding and decoding.
///
class base64Encoding
{
	///	Summary:
	///	Encodes and integer to a Base64 string.
	public static string Encode(int i)
	{

		try
		{
			string s = "";
			for (int x = 1; x <= 2; x++)
			{
				s ~= cast(char)(cast(byte)(64 + (i >> 6 * (2 - x) & 0x3f)));
			}
				
			return s;
		}
		catch
		{
			return "";
		}
	}
	
	
	///	Summary:
	/// Decodes a Base64 string to an integer.
	public static int Decode(string s)
	{
		char[] val = s.dup;
		return Decode(val);
	}
	
	///	Summary:
	///	Decodes a Base64 char array to an integer.
	public static int Decode(char[] val)
	{
		try
		{
			int intTot = 0;
			int y = 0;
			for(int x = (val.length - 1); x >= 0; x--)
			{
				int intTmp = cast(int)(cast(byte)val[x] - 64);
				if (y > 0)
				{
					intTmp = intTmp * cast(int)(pow(64, y));
				}
				intTot += intTmp;
				y++;
			}
			return intTot;
		}
		catch
		{
			return -1;
		}
	}
	
	
}

This code is written for the D programming language. If you don't know what D is, long story short: C++ with Garbage Collection (optionally removed @nogc) and no enforced backwards compatibility with C so it's a beautiful and quite powerful language. Facebook is investing heavily in D, worth a look. No need to obfuscate your already terrible C#, becomes compiled into native code.

Anyway back to 4chan.

~ Moogly

P.S. If you don't know what this is for, don't worry, I leave this here for those who love this kind of thing, and for future developers who may need it. Maybe next time as I browse through 4chan more code will pop up into my editor again.

usage:
Code:
void main()
{
base64Encoding b64 = new base64Encoding();
int x = 1;
string encodedX = b64.Encode(x); // Gives back "@A"
writefln("Converting %s from Base64> %d", y, decodedY);
}
Btw you can paste all this code in 1 file, just put main @ the very bottom.

PPS:

Screenshot of it working!
KoMDuv1 - Habbo Base64 [D programming language] - RaGEZONE Forums


PPPS:

TUNNEL SNAKES RULE!
 

Attachments

You must be registered for see attachments list
Joined
Mar 7, 2007
Messages
526
Reaction score
181
Thanks moogly!

here the C# version

Code:
 ///    Summary:
    ///    Provides Base64 encoding and decoding.
    class base64Encoding
    {
        ///    Summary:
        ///    Encodes and integer to a Base64 string.
        public static string Encode(int i)
        {
            try
            {
                string s = string.Empty;


                for (int x = 1; x <= 2; x++)
                    s += (char)(byte)(64 + (i >> 6 * (2 - x) & 0x3f));


                return s;
            }
            catch
            {
                return string.Empty;
            }
        }


        ///    Summary:
        /// Decodes a Base64 string to an integer.
        public static int Decode(string s)
        {
            char[] val = s.ToArray();


            return Decode(val);
        }


        ///    Summary:
        ///    Decodes a Base64 char array to an integer.
        public static int Decode(char[] val)
        {
            try
            {
                int intTot = 0;
                int y = 0;
             
                for (int x = (val.Length - 1); x >= 0; x--)
                {
                    int intTmp = (int)((byte)val[x] - 64);
                    if (y > 0)
                        intTmp = intTmp * (int)(Math.Pow(64, y));


                    intTot += intTmp;
                    y++;
                }


                return intTot;
            }
            catch
            {
                return -1;
            }
        }
    }
 
Joined
Aug 10, 2011
Messages
7,399
Reaction score
3,307
Thanks moogly!

here the C# version

Code:
 ///    Summary:
    ///    Provides Base64 encoding and decoding.
    class base64Encoding
    {
        ///    Summary:
        ///    Encodes and integer to a Base64 string.
        public static string Encode(int i)
        {
            try
            {
                string s = string.Empty;


                for (int x = 1; x <= 2; x++)
                    s += (char)(byte)(64 + (i >> 6 * (2 - x) & 0x3f));


                return s;
            }
            catch
            {
                return string.Empty;
            }
        }


        ///    Summary:
        /// Decodes a Base64 string to an integer.
        public static int Decode(string s)
        {
            char[] val = s.ToArray();


            return Decode(val);
        }


        ///    Summary:
        ///    Decodes a Base64 char array to an integer.
        public static int Decode(char[] val)
        {
            try
            {
                int intTot = 0;
                int y = 0;
             
                for (int x = (val.Length - 1); x >= 0; x--)
                {
                    int intTmp = (int)((byte)val[x] - 64);
                    if (y > 0)
                        intTmp = intTmp * (int)(Math.Pow(64, y));


                    intTot += intTmp;
                    y++;
                }


                return intTot;
            }
            catch
            {
                return -1;
            }
        }
    }

If I sometimes want to decode an char[] which would return -1, how am I sure it had not thrown any exception?

There is nothing to try catch.
 
Joined
Aug 10, 2011
Messages
7,399
Reaction score
3,307
(Un)signed integers (16/32/64) & byte support C#
Code:
public static string Encode(IConvertible o)
    {
        try
        {

            byte[] data = BitConverter.GetBytes((dynamic)o);

            string s = string.Empty;

            for (int x = 1; x <= data.Length; x++)
                s += (char)(byte)(64 + ((dynamic)o >> 6 * (data.Length - x) & 0x3f));


            return s;
        }
        catch
        {
            return string.Empty;
        }
    }

    public static dynamic Decode<T>(string s)
    {
        char[] val = s.ToArray();

        return Decode<T>(val);
    }

    public static T Decode<T>(char[] val)
    {
        T total = (T)Convert.ChangeType(0, typeof(T));
        int y = 0;

        for (int x = (val.Length - 1); x >= 0; x--)
        {
            total += (dynamic)(T)Convert.ChangeType(((val[x] - 64) * (y > 0 ? Math.Pow(64, y) : 1)), typeof(T));

            y++;
        }

        return total;
    }

Example usage:

Code:
byte aNumber = 13;

string encodedString = base64Encoding.Encode(aNumber);

Console.WriteLine("Encoded: " + aNumber + ". Result: " + encodedString);

Console.WriteLine("Decoding: " + encodedString + ". Result: " + base64Encoding.Decode<int>(encodedString));

And I'm pretty sure it is vl64 encoding (wire encoding for old Habbo protocol) as base64 looks different.

vista4life his version only supports nothing bigger than (2^12) -1
 
Last edited:
Software Engineer
Loyal Member
Joined
Feb 19, 2008
Messages
1,055
Reaction score
492
@FullmetalPride it's coded in the D programming language, not C#. vista4life rewrote it in C#. As for the exception, I took it out as well. This is based off the encoding class found in Woodpecker. It was translated from it. Lovely how D and C# can correlate so well. :)

The wire encoding code from Woodpecker:

Code:
using System;
using System.Text;
using System.Collections.Generic;

namespace Woodpecker.Specialized.Encoding
{
    /// <summary>
    /// Provides 'wire' encoding and decoding for numbers, better known as 'VL64' or 'LV64'. 
    /// </summary>
    public static class wireEncoding
    {
        /// <summary>
        /// Encodes an integer to a VL64 string.
        /// </summary>
        /// <param name="i">The integer to encode.</param>
        public static string Encode(int i)
        {
            try
            {
                byte[] res = new byte[6];
                int p = 0;
                int sP = 0;
                int bytes = 1;
                int negativeMask = i >= 0 ? 0 : 4;

                i = Math.Abs(i);
                res[p++] = (byte)(64 + (i & 3));
                for (i >>= 2; i != 0; i >>= 6)
                {
                    bytes++;
                    res[p++] = (byte)(64 + (i & 0x3f));
                }

                res[sP] = (byte)(res[sP] | bytes << 3 | negativeMask);
                return new ASCIIEncoding().GetString(res).Replace("\0", "");
            }
            catch { return ""; }
        }
        public static string Encode(uint i)
        {
            return Encode((int)i);
        }
        /// <summary>
        /// Encodes each integer in the input array and adds it to the 'wire'. Returns the result as a string.
        /// </summary>
        /// <param name="i">The integer array to wire up the values of.</param>
        public static string Encode(int[] i)
        {
            string s = "";
            foreach (int j in i)
                s += Encode(j);

            return s;
        }
        /// <summary>
        /// Encodes a boolean to a VL64 char.
        /// </summary>
        /// <param name="b">The boolean to encode.</param>
        public static char Encode(bool b)
        {
            if (b)
                return 'I';
            else
                return 'H';
        }
        /// <summary>
        /// Decodes a wire encoded string to the first encoded number in the wire.
        /// </summary>
        /// <param name="s">The write to decode.</param>
        public static int Decode(ref string s)
        {
            try
            {
                char[] raw = s.ToCharArray();
                int pos = 0;
                int i = 0;
                bool negative = (raw[pos] & 4) == 4;
                int totalBytes = raw[pos] >> 3 & 7;
                i = raw[pos] & 3;
                pos++;
                int shiftAmount = 2;
                for (int b = 1; b < totalBytes; b++)
                {
                    i |= (raw[pos] & 0x3f) << shiftAmount;
                    shiftAmount = 2 + 6 * b;
                    pos++;
                }

                if (negative == true)
                    i *= -1;
                return i;
            }
            catch { return 0; }
        }
        public static int Decode(string s)
        {
            return Decode(ref s);
        }
        /// <summary>
        /// Decodes a wire encoded string to a boolean. This is fancy.
        /// </summary>
        /// <param name="s">The wire encoded boolean to decode.</param>
        public static bool decodeBoolean(string s)
        {
            return (s == "I");
        }
        /// <summary>
        /// Decodes a wire encoded char to a boolean. This is fancy.
        /// </summary>
        /// <param name="s">The wire encoded boolean to decode.</param>
        public static bool decodeBoolean(char s)
        {
            return (s == 'I');
        }
        public static int[] decodeWire(string s)
        {
            List<int> Ret = new List<int>();
            try
            {
                while (s.Length > 0)
                {
                    int i = Decode(ref s);
                    Ret.Add(i);
                    s = s.Substring(Encode(i).Length);
                }
            }
            catch { }

            return Ret.ToArray();
        }
        public static string[] getMixedParameters(string s)
        {
            List<string> Ret = new List<string>();
            while (s.Length > 0)
            {
                int len = 0;
                string sVar = "";
                if (s[0] == '@')
                {
                    len = base64Encoding.Decode(s.Substring(0, 2));
                    sVar = s.Substring(2, len);
                    len += 2;
                }
                else
                {
                    int w = wireEncoding.Decode(ref s);
                    sVar = w.ToString();
                    len = wireEncoding.Encode(w).Length;
                }
                s = s.Substring(len);
                Ret.Add(sVar);
            }

            return Ret.ToArray();
        }
    }
}

Then there's the Base64Encoding code from Woodpecker (note the only relevant portions is the encoding / decoding methods):

Code:
using System;
using System.Collections.Generic;

namespace Woodpecker.Specialized.Encoding
{
    /// <summary>
    /// Provides Base64 encoding and decoding.
    /// </summary>
    public static class base64Encoding
    {
        /// <summary>
        /// Encodes an integer to a Base64 string.
        /// </summary>
        /// <param name="i">The integer to encode.</param>
        public static string Encode(int i)
        {
            try
            {
                string s = "";
                for (int x = 1; x <= 2; x++)
                    s += (char)((byte)(64 + (i >> 6 * (2 - x) & 0x3f)));

                return s;
            }
            catch { return ""; }
        }
        /// <summary>
        /// Decodes a Base64 string to to an integer.
        /// </summary>
        /// <param name="s">The string to decode.</param>
        public static int Decode(string s)
        {
            char[] val = s.ToCharArray();
            try
            {
                int intTot = 0;
                int y = 0;
                for (int x = (val.Length - 1); x >= 0; x--)
                {
                    int intTmp = (int)(byte)((val[x] - 64));
                    if (y > 0)
                        intTmp = intTmp * (int)(Math.Pow(64,y));
                    intTot += intTmp;
                    y++;
                }
                return intTot;
            }
            catch { return -1; }
        }
        /// <summary>
        /// Searches through a given string for the xxth parameter and returns it. If not found, then "" is returned.
        /// </summary>
        /// <param name="s">The string to search through.</param>
        /// <param name="parameterLocation">The parameter to look for, 0 will return the first parameter, 1 the second, 2 the third etc.</param>
        public static string getParameter(string s, int parameterLocation)
        {
            try
            {
                int j = 0;
                while (s.Length > 0)
                {
                    int i = Decode(s.Substring(0, 2));
                    if (j == parameterLocation)
                        return s.Substring(2, i);

                    s = s.Substring(i + 2);
                    j++;
                }
            }
            catch { }

            return "";
        }
        /// <summary>
        /// Searches through a given string for a parameter with a ID and returns it. If not found, then "" is returned.
        /// </summary>
        /// <param name="messageContent">The string to search through.</param>
        /// <param name="paramID">The ID of the parameter to get.</param>
        public static string getStructuredParameter(string s, int paramID)
        {
            try
            {
                int Cycles = 0;
                float maxCyles = s.Length / 4;
                while (Cycles <= maxCyles)
                {
                    int cID = Decode(s.Substring(0, 2));
                    int cLength = Decode(s.Substring(2, 2));
                    if (cID == paramID)
                        return s.Substring(4, cLength);

                    s = s.Substring(cLength + 4);
                }
            }
            catch { }

            return "";
        }
        /// <summary>
        /// Gets all parameters from a string encoded with Base64 headers, and returns it as a string array.
        /// </summary>
        /// <param name="messageContent">The content to get the parameters off.</param>
        public static string[] getParameters(string messageContent)
        {
            List<string> res = new List<string>();
            try
            {
                while (messageContent.Length > 0)
                {
                    int v = Decode(messageContent.Substring(0, 2));
                    res.Add(messageContent.Substring(2, v));
                    messageContent = messageContent.Substring(2 + v);
                }
            }
            catch { }

            return res.ToArray();
        }
    }
}

The General
 
Back
Top