I was recently going through the Toughest Developer Puzzle Ever. In one of the puzzles, it required the conversion of two binary strings for the username and password combination.
While I could have just as easily searched for some page with sample code or even a built-in converter, I decide to challenge myself a little more by writing some code.
Here’s the code that I came up with in C#:
//Usage examples: string binaryString = "0111001101101111011001100111010001110111011000010111001001100101"; string textString = binaryString.BitStringToText(); //results in the word "software" binaryString = "good stuff".TextToBitString(); //produces: 01100111011011110110111101100100001000000111001101110100011101010110011001100110 public static class BinaryConverterStringExtensions { private const int BITS_PER_BYTE = 8; public static string BitStringToText(this string bits) { var asciiText = new StringBuilder(); int paddingDifference = BITS_PER_BYTE - (bits.Length % BITS_PER_BYTE); if(paddingDifference < BITS_PER_BYTE) { bits = bits.PadLeft(paddingDifference + bits.Length, '0'); } for(int i = 0; i < bits.Length; i += BITS_PER_BYTE) { asciiText.Append(ConvertBinaryToChar(bits.Substring(i, BITS_PER_BYTE))); } return asciiText.ToString(); } public static string TextToBitString(this string text) { var binaryString = new StringBuilder(); foreach(char c in text) { byte num = (byte)c; string bits = string.Empty; while(num > 0) { byte rem = (byte)(num % 2); bits += rem.ToString(); num /= 2; } string reversedBits = new string(bits.Reverse().ToArray()); binaryString.Append(reversedBits.PadLeft(BITS_PER_BYTE, '0')); } return binaryString.ToString(); } private static char ConvertBinaryToChar(IEnumerable<char> binaryChars) { byte result = 0; if(IsValid(binaryChars)) { var reversedBinary = binaryChars.Reverse().ToArray(); for(int pos = 0, len = reversedBinary.Count(); pos < len; pos++) { byte n = byte.Parse(reversedBinary[pos].ToString()); result += (byte)(n * (byte)Math.Pow(2, pos)); } } return (char)result; } //Validation Logic: Throw an exception string is does not contain binary chars or is longer than 8 chars. private static bool IsValid(IEnumerable<char> binaryChars) { bool isBinary = binaryChars.All(b => b.Equals('0') || b.Equals('1')); byte result = 0; if(!isBinary) { throw new ArgumentException("Non-binary characters detected"); } else if(binaryChars.Count() > BITS_PER_BYTE) { throw new ArgumentException("Invalid string length. Needs to be 8 characters or less"); } return true; } }