abtol.c (1974B)
1 /* -*-comment-start: "//";comment-end:""-*- 2 * GNU Mes --- Maxwell Equations of Software 3 * Copyright © 2016,2017,2018,2019,2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org> 4 * Copyright © 2022,2023 Rick Masters <grick23@gmail.com> 5 * 6 * This file is part of GNU Mes. 7 * 8 * GNU Mes is free software; you can redistribute it and/or modify it 9 * under the terms of the GNU General Public License as published by 10 * the Free Software Foundation; either version 3 of the License, or (at 11 * your option) any later version. 12 * 13 * GNU Mes is distributed in the hope that it will be useful, but 14 * WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>. 20 */ 21 22 #include <mes/lib.h> 23 #include <ctype.h> 24 25 long 26 abtol (char const **p, int base) 27 { 28 char const *s = p[0]; 29 /* `long long` (≥64-bit) accumulator so values that don't fit in 32-bit 30 * signed don't sign-extend through the parse. Affects every mes-libc 31 * number parser (strtol/strtoul/strtoull, vfprintf field widths, …). 32 * Without it, tcc3 mishandles `-Wl,-Ttext=0x80200000` (riscv64 OpenSBI 33 * kernel base) and `.quad 0x00af9a000000ffff` in amd64 kernel.S. */ 34 long long i = 0; 35 int sign_p = 0; 36 int m = '0'; 37 if (base == 0) 38 base = 10; 39 while (isspace (s[0]) != 0) 40 s = s + 1; 41 if (s[0] != 0 && s[0] == '+') 42 s = s + 1; 43 if (s[0] != 0 && s[0] == '-') 44 { 45 sign_p = 1; 46 s = s + 1; 47 } 48 while (isnumber (s[0], base) != 0) 49 { 50 i = i * base; 51 if (s[0] >= 'a') 52 m = 'a' - 10; 53 else 54 { 55 if (s[0] >= 'A') 56 m = 'A' - 10; 57 else 58 m = '0'; 59 } 60 i = i + s[0] - m; 61 s = s + 1; 62 } 63 p[0] = s; 64 if (sign_p != 0) 65 return -i; 66 67 return i; 68 }