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? |
thats because atoi in stdlib.h is:
extern int atoi (__const char *__nptr) not unsigned... :( |
might want to try atol
|
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? :) |
try sprintf() or std::stringstream if you're using C++ to work with MySQL C Api.
|
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. |
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. |