How to convert each character in a character array to integer? - c

I have tried the standard methods but still I get error in my answer.
My code:
int main() {
int val;
char str[] = {'1', '45', '0'};
val = str[1] - '0';
printf("Int value = %d\n", val);
return(0);
}
I am getting answer as 5 instead of 45.
How do I solve this issue?
[update from comment:]
I actually need to process an array of strings..suppose I want to convert octal numbers to decimal, and my input has to be in the form of an array of strings. I wish to convert these no.s to decimal : {45,17,100} For that I would, at first be requiring to extract each element and change it to integer. Could you plz suggest what would be the best way to do it?

I actually need to process an array of strings
What you have defined here
char str[] = {'1', '45', '0'};
is not an array of strings, but exactly one array of char with 3 elements. It is not even a C-"string", as this would require a trailing value of 0. Note that the value of the character '0' isn't 0, but, for example, for the ASCII character set it's 48.
'45' is a multi-byte character literal, which in fact is an integer. The code above tries to initialise the 2nd element of the char-array str (str[1], which is a char) using this very literal.
This does not work.
A char cannot (necessarily) hold the int value of this multi-byte character literal. In this case the initialisation of str[1] overflows, resulting in the unexpected value of 5.
To see the issue try the following code:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char c_min = CHAR_MIN;
char c_max = CHAR_MAX;
unsigned char uc = '45';
printf("'1'=%d\n", '1');
printf("'45'=%d\n", '45');
printf("'0'=%d\n", '0');
printf("lowest possible value for char=%d\n", c_min);
printf("highest possible value for char=%d\n", c_max);
printf("'45' converted to an (unsigned) char=%u\n", uc);
return 0;
}
The example above shows how the value of 45 gets truncated when being assigned to char.
Depending on the C implementation you use the conversion of '45' to a char might even invoke the infamous Undefined Behaviour. This is not good.
What you seem to be wanting is:
#define ARRAY_SIZE_MAX 3
char * str[ARRAY_SIZE_MAX] = {"1", "45", "0"}; /*. Mind the double quotes. */
This defines an array of 3 pointers to char , with each pointing to a C-"string".

Here, you are getting 5 instead of 45 because st[1] = '5', this is because we have only ASCII value of 0 to 9 integers and 45 have no ASCII value.
To store 45 in your string you have to declare multidimensional string.
for example:
char st[3][3]={'1', '45', '0'};
Here is the working code:
#include<stdio.h>
int main(){
int i,ans,j;
char st[3][3]={{'1'}, {'4','5'},{'0'}};
for(j=0;j<3;j++){
for(i=0;st[j][i]>=48 && st[j][i]<=57;i++){
ans=st[j][i]-'0';
printf("%d",ans);
}
printf("\n");
}
return 0;
}
Output is
1
45
0

It depends, what do you want.
Every character has it's own int value- It's simply ASCII code
If you will iterate over integers and make it print like %c you will get ASCII table (you can see it eg. there.
But if you want to read int values from string / char datatype you will have to parse it- atoi (ascii to integer) function- example there
Btw I dont know how exactly your example works but the problem is you are doing following: int val = '45' - '0'; int value of '0' should be 48, '45' rly I dont know, but '4' is 52int and '5' is 53 int, so something like that..
As i wrote you should to do something like int val = atoi('45') - atoi('0') just for sure maybe better to cast into int as follows int val = (int) (atoi('45') - atoi('0')) - exactly asi in your example
int main() {
int val;
char str[] = {'1', '45', '0'};
val = (int) (atoi(str[1]) - atoi('0'));
printf("Int value = %d\n", val);
return(0);
}
Not sure, but i think that should works, hope that will help

Related

+'0' wont give char value of int

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.

How can I add to the ascii value of a char letter?

so, lets say that a char contains the letter "a":
int main() {
int i=8;
char test2[2]="a"+i;
return 0;
}
I just want to add 5 to the value of that letter's ASCII value. So that test2 would contain "h", since ASCII value of h a ASCII value of a+8.
Is there a simple way to do this? I have tried googling this, and I would think this is a basic thing to do, but I am clearly missing an easy way to do this. Would appreciate any help.
You have to add to a char, not the string:
char test2[2] = { 'a' + i, 0 };
"a" is not a character, but a string. You need single quotes to works with individual characters.
int i = 8;
char c = 'a' + i;
printf("c=%c\n", c);
Output:
c=i
In C, character holds an ACSII value (which is integer) by default. In your case, to make h out of a you have to do this:
#include <stdio.h>
int main() {
char test2 = 'a' + 7;
printf("%c\n\n", test2); // just check
return 0;
}
Haven't compiled this, but wouldn't (int)'a' + i work?
A double quote isn't a char, its a string literal.

Turning a string character into an int

Basically, I have this really long string full of digits:
char *number = "insert really long number";
Now I want to perform math operations on individual digits contained in this string, let's say the following (summing two consecutive digits in this string aka array of chars):
sum = number[i] + number[i+1];
However, this does not produce the correct result, it returns a garbage value. I know how to extract a single value with printf for example:
printf("%c", number[i]);
But how can I get this %c to use in computations as above? I tried with atoi, but I get "error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with &".
1) atoi accept string rather than single character
2) If you want to convert just one ACSII char 0 - 9 just use following code:
if(rChar >= '0' && rChar <= '9')
val = rChar - '0';
You probably want this:
char *number = "123";
int n = 0;
char c;
for (int i = 0; c = number[i]; i++)
{
n += number[i] - '0';
}
printf("n = %d\n", n);
For any number which is represented as a datatype char, you can subtract that number from '0' to get that number in integer type.
For example:
char a = '5';
int num = a - '0';
//num will store 5
Why this works?
Because if you check the ASCII value for '5', it is 53 and for '0' it is 48. So the difference is 5. This will work for converting any number in character form to integer.
The ASCII value for '0' is 48, for '1' it is 49 and so on. So the subtraction from '0' results in giving us the difference of ASCII values.
Here is a link to ASCII values: http://www.asciitable.com/
atoi convert string (const char*) to int, if you give it a char it will not work. A solution to convert a char to an int is to use the ASCII table:
char c = '9'
int v = c - '0'; // v == 9

Can i assign a integer to a character pointer array?

int k=5;
char* result = (char *)malloc(100 * sizeof(char));
result[count] = k;
Considering the above code, if I print the contents of result[count] it prints smiley symbols. I tried like below,but of no use.
result[count]=(char)k;
Can anyone help me?
I am percepting that malloc(100*sizeof(char)) will create 100 blocks each of size of character contiguously. Please correct me if I am wrong?
I'll disregard all the fluff about arrays and malloc as it is irrelevant to the problem you describe. You seem to essentially be asking "What will this code print:"
char c = 5;
printf("%c", c);
It will print the symbol 5 in your symbol table, most likely a non-printable character. When encountering non-printable characters, some implementations choose to print non-standard symbols, such as smileys.
If you want to print the number 5, you have to use a character literal:
char c = '5';
printf("%c", c);
or alternatively use poor style with "magic numbers":
char c = 53; // don't write code like this
printf("%c", c);
It is a problem of character representation. Let's begin by the opposite first. A char can be promoted to an int, but if you do you get the representation of the character (its code). Assuming you use ASCII:
char c = '5';
int i = c; // i is now 0x35 or 53 ASCII code for '5'
Your example is the opposite, 5 can be represented by a char, so result[count] = k is defined (even if you should have got a warning for possible truncation), but ASCII char for code 5 is control code ENQ and will be printed as ♣ on a windows system using code page 850 or 437.
A half portable (not specified, but is known to work on all common architectures) way to do the conversion (int) 5 -> (char) '5' is to remember that code '0' to '9' are consecutive (as are 'A' to 'Z' and 'a to 'z'), so I think that what you want is:
result[count] = '0' + k;
First, let's clean up your code a bit:
int k=5;
char* result = malloc(100);
result[count] = k;
sizeof(char) is always equal to 1 under any platform and you don't need to cast the return of malloc() in C.
This said, as long as your count variable contains a value between 0 and 99, you're not doing anything wrong. If you want to print the actual character '5', then you have to assign the ASCII value of that character (53), not just the number 5. Also, remember that if that array of chars has to be interpreted as a string, you need to terminate it with '\0':
int k=5, i;
char* result = malloc(100);
for (i=0; i<98; i++) {
result[i] = ' ';
}
result[98] = 53;
result[99] = '\0';
printf("%s\n", result);
The elements in the array you're trying to allocate are all the size of a char, 1 byte. An int is 4 bytes thus your issues. If you want to store ints in an array you could do:
int result[100];
Followed by storing the value, but honestly from the way your questioned is posed I don't know if that's actually what you're trying to do. Try rephrasing the post with what you're trying to accomplish.
Are you trying to store 5 as a character?

What is this part of the code doing?

I am new to c programming. As a part of my uni course for network security, I have to design a SSL handshake simulation. I found a sample code online, however i don't understand some parts of the code. Could you please help me with following :
What does (char) 0 do ?? ( send_data is defined as char send_data[1024]; )
send_data[0] = (char) 0; //Packet Type = hello
send_data[1] = (char) 3; //Version
EDIT + FOLLOWUP
Folks I know what type casting is.
I understand what casting is But the code I posted is doing nothing. Even though integer 0 is being cast as a character, its not doing anything because when you print it - its a blank - no value.
eg :
#include <stdio.h>
#include <stdlib.h>
int main(){
char test;
int num;
num = 1;
test = (char) num; // this does nothing
printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);
// Isn't this the correct way to do it ?? :
num = 3;
test = '3'; // now this is a character 3
printf("num = %d , %c\n",num,num);
printf("test = %d , %c\n",test,test);
return 0;
}
the output of above code is :
num = 1 ,
test = 1 ,
num = 3 ,
test = 51 , 3
So why is it being done ?? isn't this the right way to do it :- send_data[0] = '0'; send_data[1] = '3';
It simply casts the int 0 (or 3) into a char type.
It's possibly not necessary but may be used to remove warnings of possible truncation.
A better idiom would be:
send_data[0] = '\x00'; // Packet Type = hello
send_data[1] = '\x03'; // Version
since those are explicitly characters, without having to worry about casting.
Keep in mind that (char) 0 (or '\x00') is not the same as '0'. The former two give you the character code 0 (the NUL character in ASCII), the latter gives you the character code for the printable 0 character (character code 48 or '\x30' in ASCII). That's why your printing isn't acting as you seem to expect.
Whether your particular protocol requires code point 0 or printable character 0 is something you haven't made clear. If you're truly trying to emulate SSLv3, the correct values are the binary rather than printable ones as per RFC6101:
enum {
hello_request(0), client_hello(1), server_hello(2),
certificate(11), server_key_exchange (12),
certificate_request(13), server_done(14),
certificate_verify(15), client_key_exchange(16),
finished(20), (255)
} HandshakeType;
It is just casting the literal symbol into a char value. But I don't think it is necessary.
It is casting the int value into the char type.
This is known as type-conversion or casting. You do this when you need to change an entity of one data-type to another.
In your examples, 0 and 3 (integers) are being casted as type chars.
http://en.wikipedia.org/wiki/Type_conversion
send_data is defined as an array of char. But 0 and 3 are integer literals. When the integers are assigned to the array, they are being cast as char. This means that send_data [0] will hold the character with ASCII value 0, i.e. the NUL character. send_data[1] will hold the character with ASCII value 3, the end of text character.
int main()
{
char ch;
ch = (char) 0;
printf("%d\n", ch); //This will print 0
printf("%c\n", ch); //This will print nothing (character whose value is 0 which is NUL)
ch = (char) 3;
printf("%d\n", ch); //This will print 3
printf("%c\n", ch); //This will print a character whose value is 3
return 0;
}
It is type casting int type to char type.
Its good to create a demo program and test it when you get some doubts while reading.

Resources