How can I print the decimal representation of a character in c? - 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;
}

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.

You are returning address of local array.
This is both incorrect return type (char ** vs char *) and a bad thing to do at all.

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)

Related

how to print a string in c without pā” in the end of the string

so i've been writing a program that convert a decimal number to it's boolean representation but every time i compile the return value which is a string show additional characters like pā” here is the program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main (void)
{
signed char str[256];
int dec,rest;
int i = -1;
int j;
printf ("write a decimal number : ");
scanf ("%d",&dec);
do
{
rest = dec % 2;
dec/= 2;
for (j=i;j>-1;--j)
str[j+1]=str[j];
str[0]=rest+48;
++i;
} while (dec!=0);
printf ("the binary representation of this number is %s",str);
}
the output :
write a decimal number : 156
the binary representation of this number is 10011100pā”
i don't know if im missing something but i will be grateful if you guys help me
In C and C++, strings are null-terminated, this means that every valid string must end with a character with code 0. This character tells every function that is dealing with this string that it is in fact over.
In your program you create a string, signed char str[256]; and it is initially filled with random data; this means that you reserved space for 256 characters and they are all garbage, but the system does not know they are invalid. Try printing this string and see what happens.
In order to actually tell the system that your string is over after say, 8 characters, the 9th character hast to be the NUL character, or simply 0. In your code you can do it in two ways:
after the loop, assign str[i] = 0, or (even simpler)
initialize the string as signed char str[256]={0};, whiche creates the storage and fills it with nulls; after writing to the string you can be sure that the character after the last one you've written will be a NUL.
At the end of your do {} while () loop, you need to set the character after the last character in your string to 0. This is the array index of the last character you want (i) plus one. This lets printf know where your string ends. (Otherwise, how could it know?)
initialize the str variable to NUL.
void main (void)
{
signed char str[256];
int dec,rest;
int i = -1;
int j;
memset( str, '\0', sizeof(str) );
printf ("write a decimal number : ");
scanf ("%d",&dec);
do
{
rest = dec % 2;
dec/= 2;
for (j=i;j>-1;--j)
str[j+1]=str[j];
str[0]=rest+48;
++i;
} while (dec!=0);
printf ("the binary representation of this number is %s",str);
}

How to get a char from ASCII number

Hello. Im reading file using FILE and reading that using fgetc to read that.
fgetc function returns me int value of my chars in ASCII.
Now i want to print that data in char values.
How to convert my ascii numbers to chars?
You most likely don't need any conversion. If the native character set on your system is ASCII (which is the most common) then no conversion is needed. 'A' == 65 etc.
That means to print a character you just print it, with e.g. putchar or printf or any other function that allows you to print characters.
int x = 48;
printf("%c", x);
it will print 0, also you can do this
int x = 48;
char xx = (char)x;
Specify format as for a char, like so:
printf("%c", number);
printf("%c", 65); // A
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will give you the whole chart upto 200.

Passing Variables through functions C

Hello im just beginning to learn C and i want to know why im getting a problem here..
i wish to pass a char pointer
char *temp;
into a function ie call to function
checkIfUniqueCourseNo(temp,k);
with a prototype
int checkIfUniqueCourseNo(char checkchar[4],int);
and a function header
int checkIfUniqueCourseNo(char checkchar[4], int k)
Im sure im doing something really stupid here but im not sure how to fix it :(
thanks in advance. ps my error is that checkchar[4] outputs a P...
Example---
temp = "123A"
checkIfUniqueCourseNo(temp,k);
int checkIfUniqueCourseNo(char checkchar[4], int k){
printf("CheckifUniqueCourse\n");
printf("Check Value = %c \n", checkchar);
return 0;
}
Output = Check Value = P
temp = "123A"
checkIfUniqueCourseNo(temp,k);
int checkIfUniqueCourseNo(char checkchar[4], int k){
printf("CheckifUniqueCourse\n");
printf("Check Value = %c \n", checkchar);
^^^^^^^^^
return 0;
}
If you're trying to print out the first character of checkchar, then you need to change this line to either
printf("Check Value = %c\n", *checkchar);
or
printf("Check Value = %c\n", checkchar[0]);
In the context of a function parameter declaration, T a[N] and T a[] are equivalent to T *a; a is declared as a pointer to T, not an array of T.
When you wrote
printf("Check Value = %c\n", checkchar);
you lied to printf; you said the argument is supposed to be of type char, but you passed a char *. Hence the bogus output.
If you want to print out the entire string "1234", then you need to change that line to
printf("Check value = %s\n", checkchar);
This time we use the %s conversion specifier to tell printf that checkchar points to a 0-terminated array of char (a.k.a. a string).
This is not at all clear. Are you assigning any value to temp? If so, what?
It would make more sense to have your prototype as:
int checkIfUniqueCourseNo(char* checkchar, int);
Since it's not at all clear where you got the 4 from.
It's been a while since I've done C, but I can see a few problems here, temp = "123A" actually requires an array for 5 characters (one of which is to include the '\0' string terminating character).
Secondly, the line printf("Check Value = %c \n", checkchar); seems to be trying to print a memory pointer as a character, change it to the following: printf("Check Value = %s \n", checkchar); and it will output each character in the array until it hits the terminating character.
There are a couple of things to look at here, you need to take a good look at the data you have, how it is represented and what you want to do with it.
Your course code appears to be a four character string, you should know that traditionally, strings in C also include an extra byte at the end with the value of zero (NUL) so that the many string functions that exist know that they have reached the end of the string.
In your case, your four digit code takes up five bytes of memory. So wont fit well passing it into your function.
If I were you, I would pass in a pointer like so:-
int checkIfUniqueCourseNo(char* coursecode, int k ) {
int rv = -1;
if ( coursecode == NULL ) return rv;
//...
I have no idea what K is for, do you?
Once you have your sequence of bytes inside your function you can save yourself alot of hastle later by doing some simple bounds checking on the data like so:
//...
if ( strlen(coursecode) > 4 ){
fprintf(stderr,"course code too long\n");
return rv;
}
if ( strlen(coursecode) < 4 ){
fprintf(stderr,"course code too short\n");
return rv;
}
//...
You can be sure you have a 4 character string now..

Char isn't converting to int

For some reason my C program is refusing to convert elements of argv into ints, and I can't figure out why.
int main(int argc, char *argv[])
{
fprintf(stdout, "%s\n", argv[1]);
//Make conversions to int
int bufferquesize = (int)argv[1] - '0';
fprintf(stdout, "%d\n", bufferquesize);
}
And this is the output when running ./test 50:
50
-1076276207
I have tried removing the (int), throwing both a * and an & between (int) and argv[1] - the former gave me a 5 but not 50, but the latter gave me an output similar to the one above. Removing the - '0' operation doesn't help much. I also tried making a char first = argv[1] and using first for the conversion instead, and this weirdly enough gave me a 17 regardless of input.
I'm extremely confused. What is going on?
Try using atoi(argv[1]) ("ascii to int").
argv[1] is a char * not a char you can't convert a char * to an int. If you want to change the first character in argv[1] to an int you can do.
int i = (int)(argv[1][0] - '0');
I just wrote this
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv) {
printf("%s\n", argv[1]);
int i = (int)(argv[1][0] - '0');
printf("%d\n", i);
return 0;
}
and ran it like this
./testargv 1243
and got
1243
1
You are just trying to convert a char* to int, which of course doesn't make much sense. You probably need to do it like:
int bufferquesize = 0;
for (int i = 0; argv[1][i] != '\0'; ++i) {
bufferquesize *= 10; bufferquesize += argv[1][i] - '0';
}
This assumes, however, that your char* ends with '\0', which it should, but probably doesn't have to do.
(type) exists to cast types - to change the way a program looks a piece of memory. Specifically, it reads the byte encoding of the character '5' and transfers it to memory. A char* is an array of chars, and chars are one byte unsigned integers. argv[1] points to the first character. Check here for a quick explanation of pointers in C. So your "string" is represented in memory as:
['5']['0']
when you cast
int i = (int) *argv[1]
you're only casting the first element to an int, thus why you
The function you're looking for is either atoi() as mentioned by Scott Hunter, or strtol(), which I prefer because of its error detecting behaviour.

converting integers to chars in C(according to ASCII table)

been searching everywhere, but couldn't the correct answer.
the problem is pretty simple:
i have to convert ASCII integer values into char's.
for example, according to ASCII table, 108 stands for 'h' char. But when i try to convert it like this:
int i = 108
char x = i
and when I printf it, it shows me 's', no matter what number i type in(94,111...).
i tried this as well:
int i = 108;
char x = i + '0'
but i get the same problem! by the way, i have no problem in converting chars into integers, so i don't get where's the problem :/
thanks in advance
That is how you do it. You probably want it unsigned, though.
Maybe your printf is wrong?
The following is an example of it working:
// Print a to z.
int i;
for (i = 97; i <= 122; i++) {
unsigned char x = i;
printf("%c", x);
}
This prints abcdefghijklmnopqrstuvwxyz as expected. (See it at ideone)
Note, you could just as well printf("%c", i); directly; char is simply a smaller integer type.
If you're trying to do printf("%s", x);, note that this is not correct. %s means print as string, however a character is not a string.
If you do this, it'll treat the value of x as a memory address and start reading a string from there until it hits a \0. If this merely resulted in printing s, you're lucky. You're more likely to end up getting a segmentation fault doing this, as you'll end up accessing some memory that is most likely not yours. (And almost surely not what you want.)
Sounds to me like your printf statement is incorrect.
Doing printf("%c", c) where c has the value 108 will print the letter l... If you look at http://www.asciitable.com/ you'll see that 108 is not h ;)
I'm guessing your printf statement looks like this:
printf("s", x);
..when in fact you probably meant:
printf("%s", x);
...which is still wrong; this is expecting a string of characters e.g:
char* x = "Testing";
printf("%s", x);
What you really want is this:
int i = 108;
char x = i + '0';
printf("%c", x);
...which on my system outputs Ā£

Resources