Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded).markdown
Each 8 bits on the binary string represent 1 character on the ASCII table.ui
Note: In the case of an empty binary string your function should return an empty string.this
using System; using System.Collections.Generic; using System.Linq; public static class Kata { public static string BinaryToString(string binary) { int count = binary.Length / 8; string tmp = string.Empty; List<char> list = new List<char>(); for (int i = 0; i < count; i++) { tmp = binary.Substring(i * 8, 8); list.Add((char)(Convert.ToInt32(tmp,2))); } return string.Join(string.Empty,list); } }
其餘人的解法:spa
binary.Split(8)的用法,經過this關鍵字對string類進行了擴展,增長了擴展方法Split(int n)
IEnumerable<string>和yield的用法3d
Convert.ToChar的用法code
using System; using System.Linq; using System.Collections.Generic; public static class Kata { public static string BinaryToString(string binary) { return string.Join("", binary.Split(8).Select(s => Convert.ToChar(Convert.ToInt32(s, 2)))); } static IEnumerable<string> Split(this string s, int size) { for (int i = 0; i < s.Length; i += size) { yield return s.Substring(i, Math.Min(size, s.Length - i)); } } }
Encoding.GetString 方法 (Byte[])blog
using System; using System.Text; using System.Collections.Generic; public static class Kata { public static string BinaryToString(string binary) { List<Byte> byteList = new List<Byte>(); for (int i = 0; i < binary.Length; i += 8) byteList.Add(Convert.ToByte(binary.Substring(i, 8), 2)); return Encoding.ASCII.GetString(byteList.ToArray()); } }
上面版本的裝逼寫法ci
using System; using System.Text; using System.Linq; public static class Kata { public static string BinaryToString(string binary) { return Encoding.ASCII.GetString(Enumerable.Range(0, binary.Length / 8) .Select(i => binary.Substring(i * 8, 8)) .Select(s => Convert.ToByte(s, 2)).ToArray()); } }