以二进制的优点是可以做“位与“操作,速度非常快,而且计算方便。那么如何把字符串的二进制数保存呢,最好的方法就是每隔8位做一次转换为Byte,然后保存。
public static byte[] ToBytes(this string orgStr)
{
byte[] result = null;
if (HasNotContainBinaryValue(orgStr))
{
throw new FormatException("功能只能输入01");
}
else
{
#region 网上的错误算法
//var binaryBits = orgStr.ToCharArray().Select(i => (byte)(i - 48)).ToArray();
//var binarySize = orgStr.Length;
//result = new byte[binarySize];
//Array.Copy(binaryBits, result, binarySize);
#endregion
if (orgStr.Length > 8)
{
///get the lenght of byte array
int len = orgStr.Length % 8 == 0 ? orgStr.Length / 8 : (orgStr.Length / 8) + 1;
///initial the result with the length calculated previously
result = new byte[len];
/// define a varibale which will be used to split the string
///complement the length of the orgianl string, which can be dividened by 8
/// Assign the original string to another temp variable in case of confused with the original one
/// This temporary string will be renewed every time after getting the result of a subString
string tempStr = orgStr.PadLeft((8 - orgStr.Length % 8) + orgStr.Length, '0');
for (int i = 0; i < len; i++)
{
string binStr;
binStr = tempStr.Substring(i * 0, 8);
tempStr = tempStr.Substring(8, tempStr.Length - 8);
result[i] = Convert.ToByte(binStr, 2);
}
}
else
{
result = new byte[1];
result[0] = Convert.ToByte(orgStr, 2);
}
}
return result;
}