Convert a decimal higher than 9 int to char in C - c

To write into a log file, some pointer list (in C language), i would like to convert my int * into a character array before to write it, in the log file.
I know that to convert a decimal to a char buffer we could use something like below but my values could be higher than 9 and this didn't work for that.
int data = 5;
char cData = data + '0';
Have you any solutions ?
Best Regards.

Well, you can't store a decimal more than 9 in a char. I would recommend you to use a char array to store decimal greater than 9 using sprintf() defined in <stdlib.h> like this.
int data = 224;
char arr[10];
sprintf(arr, "%d", data);

A char can't hold both '1' and '0'. You would need at least two char. This is what the printf family does. printf %d will convert an int to a string that's its decimal representation.
Since you said you want to output the result, printf or fprintf might be the best options. If you want to build the string in an array, snprintf.

Related

sscanf does not correctly convert floats when size of array is fixed

I am trying to use sscanf to convert an array of char in C to a double. My issue is best described in this short minimal working example:
#include <stdio.h>
int main (int argc, char **argv)
{
char string_one[] = "1.2e-4";
char string_two[6] = "1.2e-4";
double one, two;
sscanf(string_one, "%lf", &one);
sscanf(string_two, "%lf", &two);
printf("%e, %e\n", one, two);
return 0;
}
Compiled with GCC and running the resulting executable returns 1.200000e-04, 1.200000e-41, instead of the same number twice. The issue does not appear if the floating point number I want to convert is of the form 3e4(if there is no decimal separator).
For my program I have to define an array of char with a fixed size (as I am filling the array during the course of the program), which is why I am running into this issue.
I guess the problem might be pretty obvious - but as I am a newbie in C I am out of ideas what the problem could be. Any help appreciated!
char string_two[6] = "1.2e-4"; ... sscanf(string_two, "%lf", &two); expects to scan a string. string_two[] is not a string as it lacks a null character. Result: undefined behavior (UB).
Solution: Insure string_two[] is a string.

Convert entire array of characters into integer in C

I'm reading input from a file and trying to create a numerical value from the strings I take in.
I tried simply using the atoi but that doesn't work on characters.
Then I tried using a forloop over my array of characters but then I got error because some characters are actually integers.
Then I tried using ifstatement to check if the characters themselves are integers and just add it to my "sum" manually.
But so far all I get is errors and errors, I'm not sure where my logic is wrong.
In C an array is simply a pointer right? So to access the value at a certain index I use *arr[num] right?
This is my code
char newlineC;
char input[14];
while(fscanf(fp,"%s%c",input, &newlineC)!=EOF){
int val = 0;
int x;
for(x=0; x<14; x++){
if(isdigit(*input[x])){
val = val + input[x];
}else{
int p = atoi(input[x]);
val = val + p;
}
}
I've tried the strol function... didn't work either. I've been at this for so long I feel dumb that I am stumped on something that seems so simple. Any help is appreciated.
You are passing the wrong types all over the place.
char input[14];
this declares an char array of dimension 14. input[i] is the ith char in
the array, it has type char. It's not a pointer, you cannot dereference it,
that's why *input[x] fails. In fact the compiler should have given you an
error there, this error:
invalid type argument of unary ‘*’ (have ‘int’)
The same problem with atoi. It expects a pointer to char that points to a
string. input[x] is single char, you cannot pass to atoi. Again the
compiler should have warned you.
fscanf(fp,"%s%c",input, &newlineC)
This is very clumsy. If the input is larger than 13 characters, you will
overflow the buffer. A better way would be:
fscanf(fp, "%13s%c", input, &newline);
Or even better
int val;
fscanf(fp, "%d", &val);
Another error: if you know that input[x] is a digit, then the integer that the
digit represent is input[x] - '0'. So this should be the calculation:
val = val + input[x] - '0';
Overall I would use fgets and strtol:
while(fgets(input, sizeof input, fp))
{
long int val;
char *tmp;
val = strtol(line, &tmp, 0);
if(*tmp == 0 || *tmp == '\n')
printf("An integer was read: %ld\n", val);
else
printf("More than an integer was read: '%s'\n", line);
}
If you are only converting the chars [1..0] to an integer value, all you have to do is
int main(void) {
char input[14];
scanf("%s", input);
if (isdigit(input[0])) {
int num = atoi(input);
printf("%d\n", num);
}
else {
printf("INPUT ERROR\n");
}
}
Are you wanting to process alphabet characters as well and turn them into some integer value?
Arrays in C are based on pointers, but that's not all they are. Arrays in C is just a bunch of those data types in a line in memory. That way you can just access the pointer of the lead variable, than hop down that list in order to get the next iteration of the array.
isdigit(*input[14])
This line will cause issues. Look at what input itself is. input is the pointer to your first element in that array. input is essentially saying char* input = &array[0]; So lets say you dereference that input variable without that 14, you would get the first element. So we can say that *input = array[0]; Do you see the issue here? You basically dereferenced it twice. If you had just done insdigit(input[14]) that would work a bit better.
But onto the bigger issue here. You're taking a char array, that contains only chars, and you're trying to convert them into numbers. Remember that char and int are two different data types. Go ahead and check out this table: https://upload.wikimedia.org/wikipedia/commons/d/dd/ASCII-Table.svg
Recall that chars are basically just numbers that correspond to that ASCII value. For example your computer doesn't read a letter as a D, it reads it as 68 (or the binary format of 68). For numbers it's the same concept, even if it seems like it's just a number and you should be able to add it to val, you'd first have to subtract 48 or use the atoi function on digits.
So what can you do here? I can't say for sure without knowing exactly what you're trying to do as I don't know your specific needs, but just realize that you can already convert char into ints very easily. I believe you can just add a char to an int, although I may be mistaken (I do know there's a very easy way to add a char's value though, maybe you have to cast it first?) However recall that if you want the digits to count for face value, you'd have to subtract 48 from them first.
If you want to use atoi you can, however honestly I don't see the need here, since you're already converting regular chars to numbers here. It'd be sufficient to check to see if the char value is between 48 and 58 (or whatever the actual numbers are) and if they are then you could subtract that.
Hope this helped!

C Programming: Convert Hex Int to Char*

My question is how I would go about converting something like:
int i = 0x11111111;
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
itoa is non-standard. Stay away.
One possibility is to use sprintf and the proper format specifier for hexa i.e. x and do:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
However, the problem with this computing the size of the value array. You have to do with some guesses and FAQ 12.21 is a good starting point.
The number of characters required to represent a number in any base b can be approximated by the following formula:
⌈logb(n + 1)⌉
Add a couple more to hold the 0x, if need be, and then your BIG_ENOUGH is ready.
char buffer[20];
Then:
sprintf(buffer, "%x", i);
Or:
itoa(i, buffer, 16);
Character pointer to buffer can be buffer itself (but it is const) or other variable:
char *p = buffer;
Using the sprintf() function to convert an integer to hexadecimal should accomplish your task.
Here is an example:
int i = 0x11111111;
char szHexPrintBuf[10];
int ret_code = 0;
ret_code = sprintf(szHexPrintBuf, "%x", i);
if(0 > ret_code)
{
something-bad-happend();
}
Using the sprintf() function like this -- sprintf(charBuffer, "%x", i);
-- I think will work very well.

Can we store alphanumeric values in int data type

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

Is there any char to hexadecimal function for C?

I have a char array with data from a text file and I need to convert it to hexadecimal format.
Is there such a function for C language.
Thank you in advance!
If I understand the question correctly (no guarantees there), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").
Assuming that's correct, your best bet will be to convert the input string to an integer using either sscanf() or strtol(), then use sprintf() with the %x conversion specifier to write the hex version to another string:
char text[] = "1234";
char result[SIZE]; // where SIZE is big enough to hold any converted value
int val;
val = (int) strtol(text, NULL, 0); // error checking omitted for brevity
sprintf(result, "%x", val);
I am assuming that you want to be able to display the hex values of individual byes in your array, sort of like the output of a dump command. This is a method of displaying one byte from that array.
The leading zero on the format is needed to guarantee consistent width on output.
You can upper or lower case the X, to get upper or lower case representations.
I recommend treating them as unsigned, so there is no confusion about sign bits.
unsigned char c = 0x41;
printf("%02X", c);
You can use atoi and sprintf / snprintf. Here's a simple example.
char* c = "23";
int number = atoi(c);
snprintf( buf, sizeof(buf), "%x", number );

Resources