Take the 2-minute tour ×

I have to parse a INSERT Query of SQL which is in string format. I need to distinguish between unsigned int and signed int and also with long int and unsigned long int. I would not been knowing the data type of the variable while parsing, but I cant assume the value I am parsing to be int when its actual data type is unsigned int. Provide me a solution.

share|improve this question

closed as not a real question by Vicky, BЈовић, Mat, Bo Persson, Dori Nov 10 '11 at 3:42


Why can't you assume it's a signed int until proven otherwise (and how do you ultimately determine which it is)? –  Hot Licks Nov 9 '11 at 11:22
What have you tried so far? Can you show us? –  Joachim Pileborg Nov 9 '11 at 11:23

1 Answer 1

Your question is ambigous because any number can be stored in any int datatype as long as it can hold it, so theoretically there is no way to know if 1 is stored as an int or 1 is stored as a long unsigned int. For now I suppose that you're looking for the most effective way to store an integer.

For storing an integer most space-efficiently I'd estimate the largest number that can be present in the sql query. It has to be an upper bound if the query is valid, if not then you'd have to write your own string to integer parser. I assume that it's valid. If the upper bound is known, you can just take the type that can store the largest number, and after it is parsed you can move it to a smaller type. To do this, you can use macros like INT_MAX.

For the signed/unsigned decision. I think it's personal preference how do you store them (depends on how do you want to use them later). You can store any non-negative integer in an unsigned variable and negative in signed integers.

Assuming str is a valid string containing only the integer portion of the query you can use the following snippet to get the smallest integer type that can store the variable.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int parse(char *str)
    long long tmp;

    tmp = strtoll(str, NULL, 10);
    if (tmp == LLONG_MIN || tmp == LLONG_MAX)
            printf("out of range!\n");
            return -1;
    if (tmp <= SCHAR_MAX)
            printf("Signed char!\n");
    } else if (tmp <= SHRT_MAX) {
            printf("Signed short!\n");
    } else if (tmp <= INT_MAX) {
            printf("Signed int!\n");
    } else if (tmp <= LONG_MAX) {
            printf("Signed long!\n");
    } else if (tmp <= LLONG_MAX) {
            printf("Signed long long!\n");

Gergely from toptal.com

share|improve this answer
