LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Data type conversion in C (https://www.linuxquestions.org/questions/programming-9/data-type-conversion-in-c-361927/)

zaichik 09-09-2005 09:07 PM

Data type conversion in C
 
Hello again,

I have a problem with data type conversions. I have a variable

unsigned int ipv4;

I pull information out of a MySQL database, which is stored as int(11) unsigned. You'd think they would be compatible. I retrieve a record from the table and include the column that will be stored in ipv4. It is the first column, so gets read as row[ 0 ]. In the database table, I see that the number is stored as 2479501685, which is correct. row[ 0 ] is a pointer to char, however, and when I try this:

ipv4 = atoi( row[ 0 ] );

then ipv4 comes out as 2147483647.

Actually, row[ 0 ] is one element of a MYSQL_ROW type, which, according to the MySQL C API, is "currently implemented as an array of counted byte strings". So I am assuming that one element of row can be treated as char*, which has always worked in the past.

I looked for a function like atoi() specifically for string-to-unsigned-int but found nothing.

What am I missing? Shouldn't atoi() successfully convert string to unsigned int?

axial 09-09-2005 11:14 PM

thats because atoi in stdlib.h is:

extern int atoi (__const char *__nptr)

not unsigned... :(

axial 09-09-2005 11:15 PM

might want to try atol

zaichik 09-10-2005 03:29 PM

So the issue is that atoi() returns an int instead of an unsigned int. I will try atol() as soon as I get a chance.

But there is no function specifically that returns an unsigned int? Or is this left as an exercise for the reader? :)

Hivemind 09-10-2005 03:41 PM

try sprintf() or std::stringstream if you're using C++ to work with MySQL C Api.

zaichik 09-10-2005 05:29 PM

Hi,

Maybe I wasn't clear. I am string to convert a string to an unsigned int, so sprintf() isn't going to work.

I have tried the C functions atoi() and atol() and neither of them are working correctly. The number is being stored in the mysql table as int(11) unsigned and shows up as 2479501685. When I fetch the row with that as the first field, I use

ipv4 = atoi( row[ 0 ] ); // also tried ipv4 = atol( row[ 0 ] );

but the result is coming out as 2147483647 instead of 2147483647.

Other ideas? I cannot believe that there is no way in C to convert a string to an unsigned int.

Thanks again for any ideas.

zaichik 09-10-2005 05:47 PM

Here's what I what was looking for:

ipv4 = strtoul( row[ 0 ], NULL, 10 );

After that, ipv4 = 2479501685.

Whee! Thanks for the help and ideas, folks!


All times are GMT -5. The time now is 06:46 PM.