Ethereal-dev: Re: [Ethereal-dev] new add-on: Hethereal

Note: This archive is from the project's previous web site, ethereal.com. This list is no longer active.

From: Guy Harris <gharris@xxxxxxxxxxxx>
Date: Tue, 17 Apr 2001 22:20:26 -0700
On Tue, Apr 17, 2001 at 12:17:14PM +0200, Carsten Buchenau wrote:
> Yes, this was a quick-hack to use the string_to_guint32-function. 
> This might be a dump question, but can you tell me what's the best way
> to transform a string to an integer-value?!?

My favorite way of doing it is:

	char *p;

	value = strtol(string, &p, radix);
	if (p == string || *p != '\0')
		error;

"radix" can be one of 10, 8, 16, or 0,  10, 8, and 16 mean
unconditionally interpret the string as {decimal, octal, hex}; 0 means
"interpret it as a C-style number", i.e. hex if it begins with 0x, octal
if it begins with 0, decimal otherwise.

The stuff with "p" catches

	1) a case where the very first character is illegal, e.g. "zig",
	   in which case the conversion stops there, and "p", which is
	   set to point to the first unconverted character, points to
	   the beginning of the string;

	2) a case where there's illegal junk after the string;

(the check for "p == string" catches the case of an empty string).  Omit
the "*p != '\0'" check if you're parsing a string that could contain a
number followed by other stuff, and then parse the other stuff starting
at "p".

"strtol()" skips leading white space.

There's also "strtoul()" on many platforms, although, for whatever
reason, it allows a "-" at the front of the string.

Those routines return a "long" and an "unsigned long", respectively;
that may not fit in a "guint32", so you might save the result to an
"unsigned long" and then check whether the result fits in an "unsigned
long" or not.