There are hundreds of questions on the net about this topic but are not what I'm looking for. I am looking for a way to convert a character to its ascii value.
I don't mean display the ascii value. I mean an actual value in a variable that I can use. Just changing the place holder is not going to work for this. That only displays the value. I need the actual working value. To be more specific I want to type in a character and have its ascii value saved into an int variable.
Ex.. enter 'A' and then the variable someVariable is initialized with the value 65. Then I want to add a constant value of 20 to the value 65 (or whatever the case would be for that character), to get 85, and then use that resulting number for the reference index of an array.
So you see I need to actually convert the value to an int not a char displayed as an int.
You can easily make a character an ascii value and assign it to an int like the example below. You can also add to the value and convert it to a different ascii character.
#include <stdio.h>
int main(void)
{
char c ='A';
int ascii = (int)c;//Convert to ascii value
printf("%d\n",ascii);
ascii += 20; //value is now 85
printf("%d\n",ascii);
char d = ascii - '0'; //convert back to new character.
printf("%c\n",d);
}
output:
65
85
%
Related
I was trying to make this int to char program. The +'0' in the do while loop wont convert the int value to ascii, whereas, +'0' in main is converting. I have tried many statements, but it won't work in convert() .
#include<stdio.h>
#include<string.h>
void convert(int input,char s[]);
void reverse(char s[]);
int main()
{
int input;
char string[5];
//prcharf("enter int\n");
printf("enter int\n");
scanf("%d",&input);
convert(input,string);
printf("Converted Input is : %s\n",string);
int i=54;
printf("%c\n",(i+'0')); //This give ascii char value of int
printf("out\n");
}
void convert(int input,char s[])
{
int sign,i=0;
char d;
if((sign=input)<0)
input=-input;
do
{
s[i++]='0'+input%10;//but this gives int only
} while((input/=10)>0);
if(sign<0)
s[i++]='-';
s[i]=EOF;
reverse(s);
}
void reverse(char s[])
{
int i,j;
char temp;
for(i=0,j=strlen(s)-1;i<j;i++,j--)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
Output screenshot
Code screenshot
The +'0' in the do while loop wont convert the int value to ascii
Your own screenshot shows otherwise (assuming an ASCII-based terminal).
Your code printed 56, so it printed the bytes 0x35 and 0x36, so string[0] and string[1] contain 0x35 and 0x36 respectively, and 0x35 and 0x36 are the ASCII encodings of 5 and 6 respectively.
You can also verify this by printing the elements of string individually.
for (int i=0; string[i]; ++i)
printf("%02X ", string[i]);
printf("\n");
I tried your program and it is working for the most part. I get some goofy output because of this line:
s[i]=EOF;
EOF is a negative integer macro that represents "End Of File." Its actual value is implementation defined. It appears what you actually want is a null terminator:
s[i]='\0';
That will remove any goofy characters in the output.
I would also make that string in main a little bigger. No reason we couldn't use something like
char string[12];
I would use a bare minimum of 12 which will cover you to a 32 bit INT_MAX with sign.
EDIT
It appears (based on all the comments) you may be actually trying to make a program that simply outputs characters using numeric ascii values. What the convert function actually does is converts an integer to a string representation of that integer. For example:
int num = 123; /* Integer input */
char str_num[12] = "123"; /* char array output */
convert is basically a manual implementation of itoa.
If you are trying to simply output characters given ascii codes, this is a much simpler program. First, you should understand that this code here is a mis-interpretation of what convert was trying to do:
int i=54;
printf("%c\n",(i+'0'));
The point of adding '0' previously, was to convert single digit integers to their ascii code version. For reference, use this: asciitable. For example if you wanted to convert the integer 4 to a character '4', you would add 4 to '0' which is ascii code 48 to get 52. 52 being the ascii code for the character '4'. To print out the character that is represented by ascii code, the solution is much more straightforward. As others have stated in the comments, char is a essentially a numeric type already. This will give you the desired behavior:
int i = 102 /* The actual ascii value of 'f' */
printf("%c\n", i);
That will work, but to be safe that should be cast to type char. Whether or not this is redundant may be implementation defined. I do believe that sending incorrect types to printf is undefined behavior whether it works in this case or not. Safe version:
printf("%c\n", (char) i);
So you can write the entire program in main since there is no need for the convert function:
int main()
{
/* Make initialization a habit */
int input = 0;
/* Loop through until we get a value between 0-127 */
do {
printf("enter int\n");
scanf("%d",&input);
} while (input < 0 || input > 127);
printf("Converted Input is : %c\n", (char)input);
}
We don't want anything outside of 0-127. char has a range of 256 bits (AKA a byte!) and spans from -127 to 127. If you wanted literal interpretation of higher characters, you could use unsigned char (0-255). This is undesirable on the linux terminal which is likely expecting UTF-8 characters. Values above 127 will be represent portions of multi-byte characters. If you wanted to support this, you will need a char[] and the code will become a lot more complex.
I created a simple program from the book let us c pg no.26 which is an example to illustrate and the code is somewhat like this
#include <stdio.h>
int main() {
char x,y;
int z;
x = 'a';
y = 'b';
z = x + y;
printf("%d", z);
return 0;
}
But the output i expected was the string ab (i know the z is in int but still that was the output i can think of) but instead the output was 195 which shocked me so please help me to figure this out in easy words.
Chars/letters are internally represented as numbers in terms of some protocols (e.g., Ascii or Unicode). ASCII is a popular standard to represent the most common symbols and letters. Here is the ASCII table. This table tells all the common symbols/letters in ASCII are essentially a number between 0 and 255 (ASCII has two parts: 0 to 127 is the standard ASCII; the upper range of 128 to 255 is defined in Extended ASCII; many variants of extended ASCII are used).
To put it into the context of your code, here is what happened.
// The letter/char 'a' is internally saved as 97 in the memory
// The letter/char 'b' is internally saved as 98 in the memory
x = 'a'; // this will copy 97 to x
y = 'b'; // this will copy 98 to x
z = x +y ; // 97+98=195 -> z
If you want to print "ab", you must have two chars next to each other. Here is what you should do
char z[3];
z[0]='a'; //move 'a' or 97 to the first element of z (recall in C, the index is zero-based
z[1]='b';//move 'b' or 98 to the second element or z
z[2]=0; //In C, a string is null-ended. That is, the last element must be a null (i.e.,0).
print("%s\n",z); // you will get "ab"
Alternatively, you can get "ab" in the following way based on the Ascii table:
char z[3];
z[0]=97; //move 97 to the first element of z, which is 'a' based on the ascii table
z[1]=98;//move 98 to the second element or z, which is 'b'
z[2]=0; //In C, a string is null-ended. That is, the last element must be a null (i.e.,0).
print("%s\n",z); // you will get "ab"
Edit/comment:
Considering this comment:
"Chars are signed on x86, so the range is -128 ... 127 and not 0 ... 255 as you state ".
Note that nowhere did I mention that the char type in C has a range of 0 ... 255. I refer to [0 ... 255 ] only in the context of the ASCII standard.
You summed up 97 to 98, hence the 195.
Feeding a sum of two char in an int will promote those char to int then store the result.
Then if you want that to be printed as a string, you can printf("%s\n", z);. Printing %d will interpret the variable as a decimal signed integer.
Don't print that as a string, because you don't know how far the first chars array terminator is.
Chars array in C, for many functions such as printf, don't end where its size ends, but where the terminator char (0x00 or 0 or '\0') marks its end.
I want to make a program which converts 3www2as3com0 to www.as.com but I have got trouble at the beginning; I want to convert the first number of the string (the character 3) to an integer to use functions like strncpy or strchr so when I print the int converted the program shows 51 instead of 3. What is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
/* argv[1]--->3www2as3com0*/
char *string;
char *p;
string=argv[1];
p=string;
char cond,cond2;
cond=*p; //I want to have in cond the number 3
cond2=(int)cond; //I want to convert cond (a char) to cond2(an int)
printf("%d",cond2); //It print me 51 instead of 3
return (EXIT_SUCCESS);
}
Your computer evidently encodes strings in a scheme called ASCII . (I am fairly sure most modern computers use ASCII or a superset such as UTF-8 for char* strings).
Notice how both printable and nonprintable characters are encoded as numbers. 51 is the number for the character '3'.
One of the nice features of ASCII is that all the digits have increasing codes starting from '0'.
This allows one to get the numerical value of a digit by calculating aDigitCharacter - '0'.
For example: cond2 = cond - '0';
EDIT:
You should also probably also double check that the character is indeed a digit by making sure it lies between '0' and '9';
If you want to convert a string containing more than one digit to a number you might want to use atoi.
It can be found in <stdlib.h>.
The character's integer value is the ASCII code for the digit, not the number it actually represents. You can convert by subtracting '0'.
if( c >= '0' && c <= '9' ) val = c - '0';
Seems like the strings you are using will never have negative number, so you can use atoi(), returns the integer value from char. If it encounters something that is not a number, it will get the number that builds up until then.
It is a very trivial question but I don't know why I am not getting the correct output. Here is what I am trying to do:
char sendBuffer[1000];
int count=0:
while(count<10)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
In the output, all buffer is printed correctly except the first index. I want 1,2,3 and so on to be printed at the start of the buffer but it does not work. Please Help
You need to convert that number into a character. A cheap way to do it is:
sendBuffer[0] = '0' + count;
is there anyway to display integers greater than 9
If you need that you'll want to shift to more elaborate schemes. For example, if you want to convert an integer 42 into the string "42" you can say:
#define ENOUGH ((CHAR_BIT * sizeof(int) - 1) / 3 + 2)
char str[ENOUGH];
snprint(str, sizeof str, "%d", 42);
Credit for ENOUGH goes to caf.
printf(%s,sendBuffer); should be printf("%s",sendBuffer);
Change
sendBuffer[0]=count;
to
sendBuffer[0]='0' + count;
i.e. convert the integer 0...9 to the characters '0' ... '9'
Also add a quote i.e. printf("%s",sendBuffer);
Quoted from the question:
In the output, all buffer is printed correctly except the first
index.i want 1,2,3 and so on to be printed at the start of the buffer
but it does not work. Please Help
I think her problem is that she does not get any output for the first line. That is because in the first iteration, count is 0, i.e. sendBuffer[0] is 0 which is the '\0' character. Hence the string is treated as empty.
You are trying to print the ascii characters corresponding to decimal values 0-9 which are non-printable characters. If you need to print decimal 0-9 then initialise count to 48 which is the ascii decimal code for '0' and change the condition in the while block to count < 58; 57 is the ascii deciaml code for '9'. See below:
char sendBuffer[1000];
int count=48:
while(count<58)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
To convert an integer value to a char representation, add the value of the character '0':
sendBuffer[0]=count + '0';
Notice that's the character '0', not the number 0. This is because of how ascii values work. The char with a literal value of 0 is \0, the null terminator. Digit '0' has a literal value of 48, '1' 49 and so on.
This works for the digits 0-9. You can't put a char representation of a number bigger than that in a single char, obviously.
char sendBuffer[1000];
// take fixed stuff outside the loop
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
// it's best not to rely on order of ASCII values
for(char* numbers="0123456789"; *numbers!=0; numbers++){// use for loop for numbers
sendBuffer[0] = *numbers;
printf("%s",sendBuffer);
}
Can alphanumeric values be stored in an int data type or do we need a char to store it?
Alphanumeric values are not values. They are numbers like everything else, but they follow a specified mapping numer -> character.
For example character 'A' is 65 according to ASCII encoding. The only difference is how you treat them: if you treat them as numbers then you print out them as numbers, otherwise you print their encoding. A char data type is just an int which has size of 1 byte. Just because 1 byte is enough to store the whole extended ASCII table. There is no real 'character' data type.
Short answer: yes.
Yes, you can store characters in int data types. A char is just a integer data type like int, but with a narrower guaranteed range.
In fact, it is sometimes the right thing to do to use int rather than char to store a character - for example, if you are reading characters from a file, you can use:
int c;
while ((c = getc(file)) != EOF)
{
/* Do something with c */
In this case, you must use int rather than char for the type of c in order to be able to distinguish EOF from a valid character.
char is a single byte datatype (and hence can have values from 0 to 255).
It has a number -> char mappping.
#include <stdio.h>
int main() {
char c = 'a';
int n = c;
printf("Character '%c' stored in int as %d\n", c, n);
}
Output:
Character 'a' stored in int as 97
You can store characters in int data types. A char is an integer data type like int that can be stored in a single byte. The char data type is capable of storing the ASCII character set (256 characters). The ASCII mapping maps numbers in the range of 0-255 to characters. Since char is an integer data type, you can store the number associated with the character in the intthrough assignment operation