【问题标题】:How to print binary array as characters如何将二进制数组打印为字符
【发布时间】:2014-04-14 00:32:43
【问题描述】:

我有一个包含 28 个整数的数组,这些整数都是 1 和 0。但是,我需要将此信息打印为 4 个字符,那么如何让每 7 个字节的数据变为一位以便打印。

不确定这是否有意义,所以我将说明我需要做什么:

现在我的数组(按顺序)是这样的:0101101111011101011000100010 但我需要以某种方式获取前 7 个数字 (0101101) 并将其打印为 Z,然后使用接下来的 7、下一个 7...

感谢您的帮助!

【问题讨论】:

  • 你用什么语言写的?
  • 接受您的意见0101101。如果你把它留给0,你会得到00101101 = 0x2D = '-'。如果你用0 填充它,你会得到01011010 = 0x5A = 'Z'。这是反直觉的。这是你真正想要的,在右边填充一个零吗?
  • @R Sahu 位将被解释为小端,而不是大。
  • 前2组7个看起来像“Zw”,但后2组不是“+Z”。
  • @chux 这是一般做法吗?如果您手头有参考资料,我很乐意阅读该主题。

标签: c arrays printing binary character


【解决方案1】:

我认为这可能是您正在寻找的东西。

int to_int(int *bits) {
   int power = 2;
   int digit = 1;
   int value = 0;

   int i=0;
   for(i=0; i <= 6; i++) {
        if(bits[i] == 1) {
            value += digit;
        }
        digit *= power;
    }

    return value;
}  


int main() {
    int myArray[28] = {0, 1, 0, 1, 1, 0, 1,
                    1, 1, 1, 0, 1, 1, 1,
                    0, 1, 0, 1, 1, 0, 0,
                    0, 1, 0, 0 ,0, 1, 0};

    char theChars[5];
    theChars[0] = to_char(&myArray[0]);
    theChars[1] = to_char(&myArray[7]);
    theChars[2] = to_char(&myArray[14]);
    theChars[3] = to_char(&myArray[21]);
    theChars[4] = '\0';
    printf("%s\n",&theChars[0]);
}

另外,我认为您的预期输出不正确。

【讨论】:

    【解决方案2】:

    好吧,总是有愚蠢的方法: 每 7 个区块循环一次。

    int bytes=7;
    for(int i=0; i++;i<4){
         double ASCII = 0;
         for(int j=0; i++;j<bytes){
         ASCII+=Math.pow(2, bytes-j-1)*array[i*bytes + j]
         }
         char c = (char) ASCII // you'll have some trouble with types here
    }
    

    【讨论】:

      【解决方案3】:

      假设你的输入数组被称为inputBits[] 试试这样的:

      const int input_bit_count = 28;
      char output[input_bit_count / 7];
      int outIdx = 0;
      
      // step through the bit stream converting bits to 7-bit characters
      for( int inIdx = 0; inIdx < input_bit_count; ){
          // shift over and add the next bit to this character
          output[outIdx] <<= 1;
          if( inputBits[inIdx] != 0 ){
              output[outIdx] |= 1;
          }
      
          inIdx++;
          if( inIdx % 7 == 0)
              // after each 7 bits, increment to next output character
              outIdx++;
      }
      
      // done processing, now print it out
      for( int chIdx = 0; chIdx < input_bit_count / 7; chIdx++ ){
          printf( "%c", output[chIdx] );
      }
      

      【讨论】:

      • 当我尝试我的输出是:AMv3 我的输出应该是:Zw+Z"
      • 那你有什么尝试?也许如果您发布一些代码,我们可以帮助您调试它。另外,我只是将位顺序倒了,所以将 if 语句更改为 if( inputBits[input_bit_count - inIdx - 1] != 0 )
      • 1) output[] 未初始化为 0,因此 output[outIdx] &lt;&lt;= 1; 正在移动随机数据。 2)我怀疑这些位是小端的。这个解决方案假设很大。
      猜你喜欢
      • 2017-12-20
      • 2011-01-24
      • 2022-11-29
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多