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

本文介绍了一种将二进制字符串高效转换为Byte数组的方法。通过每8位进行一次转换,确保了数据的正确性和存储效率。适用于需要处理大量二进制数据的应用场景。

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

### 声明二维数组C# 中,二维数组的声明方式与一维数组类似,但需要在数据类型后加上逗号来表示维度。例如: ```csharp int[,] matrix; ``` 这行代码声明了一个名为 `matrix` 的二维数组,其中存储的是整数类型的数据。需要注意的是,此时数组尚未分配内存空间,只是一个变量引用。 ### 初始化二维数组 C# 提供了多种方式来初始化二维数组。主要分为两种方式:使用 `new` 关键字和使用字面值初始化。 #### 使用 `new` 关键字初始化 这种方式适用于在运行时动态指定数组的大小和内容: ```csharp int[,] matrix = new int[2, 3]; ``` 上面的代码创建了一个 2 行 3 列的二维数组,所有元素的初始值为默认值(对于 `int` 类型是 0)。 #### 使用字面值初始化 如果在声明数组时就知道其内容,可以直接使用字面值进行初始化: ```csharp int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; ``` 这行代码创建了一个 2 行 3 列的二维数组,并分别赋值为 `1, 2, 3` 和 `4, 5, 6`。 ### 访问和操作二维数组元素 二维数组的访问方式与一维数组类似,使用索引访问。索引从 0 开始,第一个索引表示行,第二个索引表示列: ```csharp int value = matrix[0, 1]; // 访问第一行第二列的元素 matrix[1, 2] = 10; // 修改第二行第三列的值为 10 ``` #### 遍历二维数组 可以使用嵌套的 `for` 循环来遍历二维数组中的所有元素: ```csharp for (int i = 0; i <= matrix.GetUpperBound(0); i++) { for (int j = 0; j <= matrix.GetUpperBound(1); j++) { Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]); } } ``` `GetUpperBound(0)` 返回数组的第一维(行数)的上限索引,而 `GetUpperBound(1)` 返回第二维(列数)的上限索引。 ### 示例代码 以下是一个完整的示例,展示如何声明、初始化和遍历一个二维数组: ```csharp using System; class Program { static void Main() { // 使用字面值初始化二维数组 int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; // 遍历二维数组 for (int i = 0; i <= matrix.GetUpperBound(0); i++) { for (int j = 0; j <= matrix.GetUpperBound(1); j++) { Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]); } } } } ``` ### 注意事项 - **静态大小**:C# 中的数组是静态结构,一旦初始化后,其大小不可更改。如果需要动态调整数组大小,可以使用 `List<T>` 或其他动态集合类。 - **性能优化**:在处理大规模数据时,建议避免频繁的数组复制操作,而是使用 `List<T>` 或 `Array.Resize` 方法进行优化。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值