将 printf 转移到某个变量

Transfer printf to some variable

我已经将数组的元素传输到 string/bits 的 printf,我需要将其传输到某些 变量 ,因为我然后需要使用此 text/string ( 01000001 ) 并将其转换为 char (bits => char).

//main
bool bits2[8] = {0,1,0,0,0,0,0,1};
printf("%c\n", decode_byte(bits2));

//function
char decode_byte(const bool bits[8]){
  int i;

  for (i=0; i<8; i++){
    printf("%d", bits[i]);
  }
  
  
  return 0;
}

你在找这个吗?

#include <stdio.h>

int main() {
  bool bits2[8] = { 0,1,0,0,0,0,0,1 };
  unsigned char c = 0;

  for (int i = 0; i < 8; i++)
  {
    c <<= 1;
    c |= bits2[i];
  }

  printf("%02x\n", c);
}
//function
char decode_byte(const bool bits[8]){
  int sum = 0;
  for(int i=0;i<8;i++){
      sum += (1<<i)*bits[7-i];
  }
  return (char)sum;
}

了解 ascii table。当sum为65时,其asciitable的类型转换值为'A'

decode_byte 应该只是从二进制表示转换为实际整数:

#include <stdbool.h>
#include <stdio.h>

char decode_byte(const bool bits[8]) {
    unsigned char c = 0;

    for (int i = 0; i < 8; i++) {
        c = (c << 1) | bits2[i];
    }
    return c;
}

int main() {
    bool bits2[8] = { 0, 1, 0, 0, 0, 0, 0, 1 };
    printf("%c\n", decode_byte(bits2));
    return 0;
}

程序应该输出A,即编码为65的ASCII字符,其二进制表示为01000001.