linux C string to int [closed] - c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to convert this string "09195462965" to an int but I'm running into problems.
snippet of my code:
int n, p, pnum=0;
char buffer[256];
char *endptr;
long pnumber;
bzero(buffer,256);
p = read(sock,buffer,255);
pnumber = strtol(buffer, &endptr, pnum);
printf("n: %ld",pnumber);
p = write(sock,buffer,sizeof(buffer));
A client sends a string of "09195462965" then the server receives it.
Now on the server that string must be turned into an int i.e. 09195462965.
Note: the server sends the number as string.

You're using strtol() incorrectly, the last parameter should be the base that you want. For example if you want to store that number in base 10 (decimal):
long pnumber;
pnumber = strtol("09195462965", NULL, 10); //nst char *nptr is "09195462965"
//char **endptr is null
//int base is 10 for decimal
printf("n: %ld",pnumber);
>> 9195462965
Make sure you read the man page for the function you're using.
Passing pnum (which is set to 0) as your doing for the last parameter is causing it to spit back "0", because of the number you're passing in.
09195462965 has digits from 0-9 (so I assume you wanted dec) if you pass in "0" to strtol() then it's going to see that first 0 and will treat the number has octal, the problem with that is that octal numbers go from 0-7, thus the 9's are "out of bounds" for an octal number and as such strtol() spits back 0.
with a number like: 07175462765, you'd be fine to pass in pnum when it's 0.

That's too big to fit in an int. Try strtoumax and store it in an uintmax_t.
uintmax_t pnumber = strtoumax(buffer, &endptr, 10);
if (pnumber == UINTMAX_MAX && errno == ERANGE)
/* Too big. */
Alternatively, if you don't have strtoumax you can try strtoull et al.

Related

How to convert a string to an integer in C programming language, based on this strict example? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Example:
// variable fixed
Char specialstring[PATH_MAX];
int integernumber;
int xx = 1 ;
int yy = 1 ;
strncopy( specialstring, "1369", ... bla);
// here we go !! help there below please
integernumber=atoi(specialstring);
mvprintw( yy , xx , "%d" , integernumber );
Please help me in the way to convert the specialstring to an integer?
thank you
In your code, you have two mistakes:
1) strncopy is not the function you wants its strncpy. its man page:
char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
Here s1 is destination string and s2 is source string , n is number of chars you wants to copy from source.
So correct:
strncopy( specialstring, "1369", ... bla);
^ ^ should be `n` num of chars you wants to
strncpy copy in `specialstring`
into
strncpy( specialstring, "1369", 4);
2) In declaration of specialstring, Char is wrong you should write small c
Char specialstring[PATH_MAX];
^ small letter
char specialstring[PATH_MAX];
3) atoi() is correct function you got to convert a string into int, if you wants to convert without atoi you can use sscanf() function like:
sscanf(specialstring,"%d", &integernumber);
View this: Working Code
You can use this to convert string to int without using atoi
int Convert(char * str)
{
int result =0;
int len=strlen(str);
for(int i=0,j=len-1;i<len;i++,j--)
{
result += ((int)str[i] - 48)*pow(10,j);
}
return result;
}

I am trying to display a float value on an lcd , for the same I have to first convert it to a string.But it just doesn't work [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
weather.outdooe_temp is a float value which is being updated every time I press a button. set_temp is a float to ascii function. If I use that the thing works, but not if I use the code below.
char Thermo_Buff66[4];
static void SetBox(ScreenObj_t const *pS, EVENT_MSG const *pMsg)
{
//set_temp(weather.outdoor_temp,&a);//it works if i use this function.
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
(void)sprintf(Thermo_Buff,"%s\xc2\xb0""",Thermo_Buff66);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
//currently displaying any # value....!!ing!!
}
char Thermo_Buff66[4];
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
The buffer you have allocated (Thermo_Buff66) is too short for a floating number representing outdoor temperature (often 2 digits) plus a . plus a digit after. Indeed, it doesn't have space for the terminating '\0' character. So immediate correction would be to set the size to 5. Still, in case of armageddon (or simply being in a non-SI country ... cough ... US), the temperature could even get to above 100, in which case again you overflow your buffer. Do yourself a favor and use snprintf.
Regardless, you sprintf into a buffer, then using %s you sprintf it into something else, which there is no point to. You can do it all directly in one, removing Thermo_Buff66 altogether:
(void)sprintf(Thermo_Buff, "%.1f\xc2\xb0", weather.outdoor_temp);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
Side note: the . and the precision digit already take up 2 characters. Setting minimum width to 2 is therefore reduntant. Perhaps you thought the 2 in %2.1 is the number of digits before the .? Well it's not. It's the minimum overall width.

How to convert an integer to a character array using C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to convert an integer number to a character array in C.
Input:
int num = 221234;
The result is equivalent to:
char arr[6];
arr[0] = '2';
arr[1] = '2';
arr[2] = '1';
arr[3] = '2';
arr[4] = '3';
arr[5] = '4';
How can I do this?
Make use of the log10 function to determine the number of digits and do like below:
char * toArray(int number)
{
int n = log10(number) + 1;
int i;
char *numberArray = calloc(n, sizeof(char));
for (i = n-1; i >= 0; --i, number /= 10)
{
numberArray[i] = (number % 10) + '0';
}
return numberArray;
}
Or the other option is sprintf(yourCharArray,"%ld", intNumber);
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'.
For example, If an integer uses 32 bits, it has up to 10 decimal digits.
So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
The easy way is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintf gives you formatting options that itoa doesn't.
Use itoa, as is shown here.
char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);
buf will be a string array as you documented. You might need to increase the size of the buffer.
You may give a shot at using itoa. Another alternative is to use sprintf.

Finding min and max from data file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to write a simple program that reads integers from a data file and outputs the minimum and maximum value. The first integer of the input file will indicate how many more integers will be read, and then the integers will be listed.
Example input file:
5 100 -25 42235 7 -1
As simple as this is, i'm not sure where to start. I imagine I will need to create an array of size = the first integer, then increment my position in the array and compare to a min/max value.
I am not sure what the syntax would be to declare an array with the first integer, then fill the array with the remaining integers, or if that is even the right approach. After creating the array, I should have no problem assigning values to min/max variables with a loop increasing position through the array.
You don't need an array. Just keep track of the current minimum and maximum (they start as the first number you read). After you read each number, if it's lower than the minimum it becomes the new minimum, and if it's higher than the maximum it becomes the maximum.
There is no need to use an array to store data. You just need to find out minimum and maximum values from data received from a file.
long lMin = 0, lMax = 0;
int nCount;
long lNo;
// open file
fscanf( file, "%d", &nCount );
for( int i = 0; i < nCount; i++ )
{
fscanf( file, "%ld", &lNo );
if( lNo > lMax )
lMax = lNo;
if( lNo < lMin )
lMin = lNo;
}
printf(" Min = %ld Max = %ld\n", lMin, lMax );
// close file

How to convert from ASCII to Hex and vice versa? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to convert ASCII to HEX and HEX to ASCII by using a C program.
How can I do that?
Here's a simplistic function to convert one character to a hexadecimal string.
char hexDigit(unsigned n)
{
if (n < 10) {
return n + '0';
} else {
return (n - 10) + 'A';
}
}
void charToHex(char c, char hex[3])
{
hex[0] = hexDigit(c / 0x10);
hex[1] = hexDigit(c % 0x10);
hex[2] = '\0';
}
Its pretty easy. Scan through character by character ... best to start from the end. If the character is a number between 0 and 9 or a letter between a and f then place it in the correct position by left shifting it by the number of digits you've found so far.
For converting to a string then you do similar but first you mask and right shift the values. You then convert them to the character and place them in the string.

Resources