Home > Enterprise >  convert decimal(letters) to binary
convert decimal(letters) to binary

Time:11-29

I have to convert a letter to binary number. All work but with one problem - I don`t understand why after my binary number it still prints some other numbers... Can someone help, please?

Here is my code. Thank you in advance!

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

void convert(const char char, bool bits[8]) {
    char c = char;
    for (int j = 7; j 1 > 0; j--){
        if(c>=(1<<j)){
            c=c-(1<<j);
            printf("1");
        }else{
        printf("0");
        }
    }
//here start to prints other numbers
    printf("\n");
    printf("\n");
}


int main(){
    bool bits1[8];
    encode_char('A', bits1);
    for(int i = 0; i < 8; i  )
{
    printf("%d", bits1[i]);
}
    printf("\n");
return0;
}

CodePudding user response:

There are 3 problems making your sample code unable to compile:

  1. You tried to declare the first argument to your function as const char char, but char is a type and is not valid variable name.
  2. You tried to call encode_char in main, but you defined convert
  3. return0 should be return 0

After fixing those, there will still be a problem with garbage values. Because even though you passed bits, the function never does anything with it (so it remains with garbage values). So your printf("%d", bits1[i]); will be just a bunch of "random" numbers. The extra numbers are not from what you marked with //here....

Here is an example that assigns useful values to bits:

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

void encode_char(const char input_char, bool bits[8]) {
    char c = input_char;
    for (int j = 7; j >= 0; j--){
        if(c>=(1<<j)){
            c=c-(1<<j);
            bits[7-j] = 1;
        }else{
            bits[7-j] = 0;
        }
    } 
}


int main(){
    bool bits1[8];
    encode_char('A', bits1);
    for(int i = 0; i < 8; i  )
    {
        printf("%d", bits1[i]);
    }
    printf("\n");
    return 0;
}
  • Related