user2426316
user2426316

Reputation: 7331

How can I print the decimal representation of a character in c?

I am trying to figure out how to print the ascii value of a character in binary. Here is what I have done so far, but it does not work at all and I dont know why. Can someone of you C wizards help me??

#include <stdio.h>

int main(int argc, char** argv) 
{
    char myChar;

    printf("Enter a character:\n");
    scanf("%c", &myChar);
    printf("Your character is %c\n", myChar);
    printf("ASCII in BIN: %c\n", toBinary(myChar));

    return 0;
}

char* toBinary(int decimalNumber) 
{
    char binaryValue[7] = "";
    for (int i = sizeof(binaryValue); i >= 0; ++i) 
    {
        int remainder = decimalNumber % 2; 
        decimalNumber = decimalNumber / 2;

        binaryValue[i] = remainder;
    }
    return &binaryValue;
}

Upvotes: 0

Views: 694

Answers (3)

Dan
Dan

Reputation: 4502

The %c format string will always interpret the corresponding printf argument as a character. In this case, its probably not what you want.

printf("ASCII in BIN: %d\n", myChar);

will print out the ascii code point of myChar just by telling printf to treat it as a number.

If you'd like to print out the string being returned by your toBinary function, you can do that with

printf("ASCII in BIN: %s\n", toBinary(myChar));

There's a good reference of the various % codes and what they mean here.


However, it's also worth noting that your toBinary function probably doesn't do what you want. This loop condition:

for (int i = sizeof(binaryValue); i >= 0; ++i) 

will start at sizeof(int) and count up until it runs out of integers, then stop only because INT_MAX + 1 == INT_MIN. Because you're using i as an array index, this will almost certainly crash your program.

You also need to make sure to terminate the string you're generating with a '\0', as that is how subsequent calls to printf will recognize the string has ended.

And, as noted in other answers, your toBinary implementation is also returning a pointer to a memory address that will get automatically deleted as soon as toBinary returns.

Upvotes: 2

Kevin Dong
Kevin Dong

Reputation: 5359

printf("ASCII in BIN: %c\n", toBinary(myChar));

%c is to print a character.

And, there is no BOOL type in C, so you can change it in to a string, and pass the pointer to an array to printf("%s", pointer)

Upvotes: 0

aragaer
aragaer

Reputation: 17848

You are returning address of local array.

This is both incorrect return type (char ** vs char *) and a bad thing to do at all.

Upvotes: 0

Related Questions