【问题标题】:how to convert an array of integers (1s and 0s) to their ascii equivalents in c#如何将整数数组(1和0)转换为c#中的ascii等价物
【发布时间】:2019-07-14 13:41:26
【问题描述】:

我有一个整数 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。

【问题讨论】:

  • 就存储位序列而不是字符串的更好方法而言,您可以使用BitArray
  • stackoverflow.com/questions/6006425/… First Answer有你需要的信息
  • @mheavers 我可以验证您可以创建一个包含 48 个元素的 BitArray - new BitArray(48)

标签: c# arrays binary ascii data-conversion


【解决方案1】:

尝试使用 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)));

【讨论】:

    【解决方案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),在生产级代码中,您必须清理您的输入。

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多