Crizly
Crizly

Reputation: 1009

Convert Char* Variable To uint32_t in C

I've got an Sqlite database and i'm reading values back out using this loop:

int i;

for(i=0; i<argc; i++) // [0] = IP, [1] = seq, [2] = count
{
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}

if (atoi(argv[2]) > stealthBeta)
{
    confirmSEQ((uint32_t)argv[1]);
}

The value in argv[1] is stored as an UNSIGNED INT in the database and is being written out to the console properly but when I call the function I'm getting the wrong number.

I've tried casting it but it's not exactly working. What's the proper way to get it from the char* to uint32_t?

Upvotes: 0

Views: 5534

Answers (2)

Konstantin Dedov
Konstantin Dedov

Reputation: 425

Use atoi() for conversion to int.

Use (unsigned)atoi() for conversion to unsigned.

For example, in your case:

if (atoi(argv[2]) > stealthBeta)
{
    confirmSEQ((uint32_t)atoi(argv[1]));
}

Upvotes: 0

chqrlie
chqrlie

Reputation: 144780

To convert a string to the number it represents, use strtol() or strtoul() from <stdlib.h>. strtoul() parses an unsigned long, guaranteed to be at least 32 bit wide. Passing 0 as the base parameter allows conversion of hexadecimal representation prefixed with 0x. Values prefixed with just 0 will be parsed as octal, otherwise parsing is done in decimal.

#include <stdlib.h>

...

if (strtol(argv[2], NULL, 0) > stealthBeta) {
    confirmSEQ((uint32_t)strtoul(argv[1], NULL, 0));
}

Upvotes: 1

Related Questions