如何在 C# 中将整数数组(1 和 0)转换为它们的 ascii 等价物

how to convert an array of integers (1s and 0s) to their ascii equivalents in c#

我有一个整数 1 和 0 的数组(可能需要转换为字节类型?)。我已经使用 an online ASCII to binary generator 得到这个 6 位字母序列的等效二进制:

abcdef 在二进制中应该等于 011000010110001001100011011001000110010101100110。所以在 C# 中,我的数组是 [0,1,1,0,0,0,0...],构建者:

int[] innerArr = new int[48]; 
for (int i = 0; i < 48); i++) {
    int innerIsWhite = color.val[0] > 200 ? 0 : 1;
    innerArr[i] = innerIsWhite;
}

我想获取这个数组,并将其转换为 abcdef(并且能够执行相反的操作)。

我该怎么做?有没有更好的方法来存储这些 1 和 0。

尝试使用 LinqConvert

  source = "abcdef";

  // 011000010110001001100011011001000110010101100110 
  string encoded = string.Concat(source
    .Select(c => Convert.ToString(c, 2).PadLeft(8, '0')));

  // If we want an array
  byte[] encodedArray = encoded
    .Select(c => (byte) (c - '0'))
    .ToArray();

  // string from array
  string encodedFromArray = string.Concat(encodedArray);

  // abcdef
  string decoded = string.Concat(Enumerable
    .Range(0, encoded.Length / 8)
    .Select(i => (char) Convert.ToByte(encoded.Substring(i * 8, 8), 2)));

如果您输入的是位串,那么您可以使用如下方法将其转换为字符串

public static string GetStringFromAsciiBitString(string bitString) {
    var asciiiByteData = new byte[bitString.Length / 8];
    for (int i = 0, j = 0; i < asciiiByteData.Length; ++i, j+= 8)
        asciiiByteData[i] = Convert.ToByte(bitString.Substring(j, 8), 2);
    return Encoding.ASCII.GetString(asciiiByteData);
}

上面的代码简单地使用了 Convert.ToByte 方法,要求它进行 base-2 字符串到字节的转换。然后使用 Encoding.ASCII.GetString,从字节数组

中获取字符串表示形式

在我的代码中,我假定您的位串是干净的(8 的倍数并且只有 0 和 1),在生产级代码中您必须清理您的输入。