Unique String Encoding With Bitwise Operations

Here is a method for encoding a string that I came up with. It is actually a fairly nice method, the strategy behind this and the idea can be added onto, but this works quite well the way it is right now and for how random the output looks when we encode the original string value.

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

// Encoding

char* objEncode = stackalloc char[originalObj.Length];
for (int i = 0; i < originalObj.Length; i++)
	int j = 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 = encodedObj[i] ^ i + 1;
	objDecode[i] = (char)j;

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

This snippet has to run in unsafe context.

Perhaps you could also use the reversed index over some constant value as well to get a more unique and refined result... Just as a reminder, we are using the stack here, not the heap, so that is just something to remember.

Leave a Reply

Your email address will not be published. Required fields are marked *