C# 二进制字符串转Byte数组的算法

以二进制的优点是可以做“位与“操作,速度非常快,而且计算方便。那么如何把字符串的二进制数保存呢,最好的方法就是每隔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;
        }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值