xref: /php-src/ext/bcmath/libbcmath/src/num2long.c (revision e56ed6e1)
1 /* num2long.c: bcmath library file. */
2 /*
3     Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
4     Copyright (C) 2000 Philip A. Nelson
5 
6     This library is free software; you can redistribute it and/or
7     modify it under the terms of the GNU Lesser General Public
8     License as published by the Free Software Foundation; either
9     version 2 of the License, or (at your option) any later version.
10 
11     This library is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14     Lesser General Public License for more details.  (LICENSE)
15 
16     You should have received a copy of the GNU Lesser General Public
17     License along with this library; if not, write to:
18 
19       The Free Software Foundation, Inc.
20       59 Temple Place, Suite 330
21       Boston, MA 02111-1307 USA.
22 
23     You may contact the author by:
24        e-mail:  philnelson@acm.org
25       us-mail:  Philip A. Nelson
26                 Computer Science Department, 9062
27                 Western Washington University
28                 Bellingham, WA 98226-9062
29 
30 *************************************************************************/
31 
32 #include "bcmath.h"
33 #include <stddef.h>
34 
35 /* Convert a number NUM to a long.  The function returns only the integer
36    part of the number.  For numbers that are too large to represent as
37    a long, this function returns a zero.  This can be detected by checking
38    the NUM for zero after having a zero returned. */
39 
bc_num2long(bc_num num)40 long bc_num2long(bc_num num)
41 {
42 	/* Extract the int value, ignore the fraction. */
43 	long val = 0;
44 	const char *nptr = num->n_value;
45 	for (size_t index = num->n_len; index > 0; index--) {
46 		char n = *nptr++;
47 
48 		if (val > LONG_MAX / BASE) {
49 			return 0;
50 		}
51 		val *= BASE;
52 
53 		if (val > LONG_MAX - n) {
54 			return 0;
55 		}
56 		val += n;
57 	}
58 
59 	/* Return the value. */
60 	if (num->n_sign == PLUS) {
61 		return (val);
62 	} else {
63 		return (-val);
64 	}
65 }
66