OnlyForFun
OnlyForFun

Reputation: 63

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

Upvotes: 0

Views: 208

Answers (3)

chqrlie
chqrlie

Reputation: 144923

decode_byte should just convert from binary representation to an actual integer:

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

The program should output A, which is the ASCII character encoded as 65, whose binary representation is 01000001.

Upvotes: 1

Fawad
Fawad

Reputation: 124

//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;
}

Read about ascii table. When sum is 65, its type converted value in ascii table is 'A'

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50831

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

Upvotes: 0

Related Questions