C# | Convert binary string ("101010101") and byte array (byte[]) to each other

insert image description here

C# | Convert binary strings to byte arrays

foreword

When we work with data in computers, it is often necessary to convert data from one format to another. And this article converts binary strings to byte arrays, which sounds common but is actually not so common.

A binary string is a string of 0s and 1s, for example: "0111010010101000".
Byte arrays are commonly used for reading and writing binary files, network communication, etc.

Binary string to byte array

The implementation idea is as follows:

  1. Calculate the length of the byte array, each 8 binary bits corresponds to a byte.
  2. Creates a byte array of the specified length.
  3. Every 8 characters of the binary string are iterated, converted to a byte and stored in a byte array.
  4. Returns the byte array.
// 将二进制字符串转换为字节数组
public static byte[] BinaryStringToByteArray(string binaryString)
{
    
    
    // 计算字节数组的长度(每8个二进制位对应一个字节)
    int numOfBytes = binaryString.Length / 8;

    // 创建字节数组
    byte[] byteArray = new byte[numOfBytes];

    // 遍历二进制字符串的每8个字符,将其转换为一个字节并存储在字节数组中
    for (int i = 0; i < numOfBytes; i++)
    {
    
    
        // 从二进制字符串中提取8个字符作为一个字节的二进制表示
        string byteString = binaryString.Substring(i * 8, 8);

        // 将字节的二进制表示转换为一个字节,并存储在字节数组中
        byteArray[i] = Convert.ToByte(byteString, 2);
    }

    // 返回字节数组
    return byteArray;
}

When traversing the binary string, this method uses the Substring method to extract 8 characters from the string. It also uses the Convert.ToByte method to convert the binary representation of a byte to a byte. The return value of this method is a byte array, where each element is a byte representing a group of eight binary bits in the original binary string.

Byte array to binary string

The implementation idea is as follows:

  1. Create a StringBuilder object to store binary strings.
  2. Iterate over each byte in the byte array.
  3. Convert each byte to a binary string and add it to a StringBuilder object. When converting, use the Convert.ToString(b, 2) method to convert the byte to a binary string, use the PadLeft method to fill the length of the string with 8 digits, and fill the insufficient digits with 0.
  4. Return the resulting binary string.
// 将字节数组转换为二进制字符串
public static string ByteArrayToBinaryString(byte[] byteArray)
{
    
    
    // 创建一个 StringBuilder 对象来存储二进制字符串
    StringBuilder binaryStringBuilder = new StringBuilder();

    // 遍历字节数组中的每个字节
    foreach (byte b in byteArray)
    {
    
    
        // 将字节转换为二进制字符串,并将结果添加到 StringBuilder 中
        // 使用PadLeft方法将字符串长度补足8位,不足的位数用0填充
        binaryStringBuilder.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
    }

    // 返回生成的二进制字符串
    return binaryStringBuilder.ToString();
}

Guess you like

Origin blog.csdn.net/lgj123xj/article/details/130097508