[C#] Fooling around with bitwise string encoding

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's a nice example of an encoding "algorithm" for strings that I came up with just 5 minutes ago actually. It works, really well to be honest.

This has not been tested extensively, but this will work for any kind of simple data encoding. I've tested with various Alt characters and that seems to work too.

Code:
//Copyright (c) AceInfinity - Tech.Reboot.Pro
//String bit encoding example

string originalObj = "Let's have ourselves a Fiesta!!!";
Console.WriteLine("Original: {0}", originalObj);
Console.WriteLine("-------------------");

// Encoding

originalObj += "\0";
char* objEncode = stackalloc char[originalObj.Length];
for (int i = 0; i < originalObj.Length; i++)
{
	int j = (int)originalObj[i] ^ (i + 1);
	objEncode[i] = (char)j;
}

string encodedObj = new string(objEncode);
Console.WriteLine("Encoded: {0}", encodedObj);

// Decoding

char* objDecode = stackalloc char[encodedObj.Length];
for (int i = 0; i < encodedObj.Length; i++)
{
	int j = (int)encodedObj[i] ^ (i + 1);
	objDecode[i] = (char)j;
}

string decodedObj = new string(objDecode);
Console.WriteLine("Decoded: {0}", decodedObj);

Result (from original code before I modified the "formula's"):
uwaXF.png


This snippet has to run in unsafe context. The reason I use (i + 1) is that the first character for both the encoded and decoded values, are the same if we just use i, because I represents an index; the first index is 0, and performing an exclusive or bitwise operation on an integer with 0 has no effect on the original value.

Code:
Console.WriteLine("{0} -> {1}", 10, 10 ^ 0);

Perhaps you could use the reversed index over some constant value as well to get a more unique and refined result.. I'm still trying to see what I can do with this.
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top