Search code examples
cvariablesbit

Transfer printf to some variable


i have transfered elements of array to printf that string/bits which I need to transfer to some variable, because i need to work then with this text/string ( 01000001 ) and convert it to 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;
}

Code + console


Solution

  • Are you looking for this?

    #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);
    }