using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace bytes
{
class Program
{
static void Main(string[] args)
{
int iterations = 1000000;
string[] binaryStrings = new string[iterations];
Random
rand = new Random
(); for (int i = 0; i < iterations; ++i)
{
string unformatedBinaryString
= GetRandomBinaryString
(rand); binaryStrings[i] = AddPrefixed0sToBinaryString(unformatedBinaryString, 8);
}
int startTime = Environment.TickCount;
for (int i = 0; i < iterations; ++i)
{
string incremented = IncrementBinary1(binaryStrings[i]);
} int totalTime1 = Environment.TickCount - startTime;
startTime = Environment.TickCount;
for (int i = 0; i < iterations; ++i)
{
string incremented = IncrementBinary2(binaryStrings[i]);
} int totalTime2 = Environment.TickCount - startTime;
Console.Out.WriteLine("IncrementBinary Xx pr0c0d3r xX : " + totalTime1);
Console.Out.WriteLine("IncrementBinary Matt : " + totalTime2);
Console.ReadKey();
}
static string GetRandomBinaryString
(Random
rand) {
int randomNumber
= rand.
Next(255); return Convert.ToString(randomNumber, 2);
}
static string AddPrefixed0sToBinaryString(string binary, int totalNeededNumberOfCharacters)
{
int numberOfCharacters = binary.Length;
int numberOf0sToAdd = totalNeededNumberOfCharacters - numberOfCharacters;
for (int i = 0; i < numberOf0sToAdd; ++i)
binary = "0" + binary;
return binary;
}
static string IncrementBinary1(string binary)
{
int number = Convert.ToInt16(binary, 2);
++number;
return Convert.ToString(number, 2);
}
static bool isBinaryString(string binary)
{
// Is the binary value over 8 characters?
if (binary.Length > 8)
return false;
// Does it contain illegal characters?
foreach (char bit in binary)
if (!bit.Equals('0') && !bit.Equals('1'))
return false;
// Everything passed.
return true;
}
static string AbsoluteZero()
{
return "00000000";
}
static char IncrementBit(char bit)
{
switch (bit)
{
case '0':
return '1';
case '1':
return '2';
default:
return '0';
}
}
static string IncrementBinary2(string binary)
{
if (isBinaryString(binary))
{
// Get all the bits, and increment the first one.
char[] bit = binary.ToCharArray();
bit[7] = IncrementBit(bit[7]);
// Loop through all the bits, and find out
// if we can push over.
for (int i = bit.Length - 1; i >= 0; i--)
if (bit[i].Equals('2'))
{
// Make sure the index isn't 0. Otherwise, we'd get an RTE trying to
// access the bit of the -1 index.
if (i != 0)
{
// Increment the next bit, and the current bit.
bit[i - 1] = IncrementBit(bit[i - 1]);
bit[i] = IncrementBit(bit[i]);
}
else
{
// This chunk of code will only be run if the current
// bit index is 0, and we need to push it over. So,
// just change it to 0.
bit[0] = '0';
}
}
// Return the binary string.
return new string(bit);
}
else
{
// Our binary string wasn't a valid one. Return the lowest possible binary
// value.
return AbsoluteZero();
}
}
}
}