Files
42_INT_01_libft/testing/srcs/test_atoi.c
2026-05-06 20:02:44 +02:00

68 lines
2.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/25 13:54:29 by hulamy #+# #+# */
/* Updated: 2019/11/25 13:54:35 by hulamy ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
// int ft_atoi(const char *str)
// {
// long long nbr; // Use `long long` to detect overflow before it happens in `int`
// int i; // Current position in the string
// int n; // Sign multiplier: 1 (positive) or -1 (negative)
// i = 0;
// n = 1;
// nbr = 0;
// // skip leading whitespace
// while (ft_isspace(str[i]))
// i++;
// // handle optional sign
// if (str[i] == '-')
// n = -1;
// if (str[i] == '+' || str[i] == '-')
// i++;
// // convert digits to integer
// while (str[i] >= '0' && str[i] <= '9')
// {
// // --- Overflow Check ---
// // LLONG_MAX = 9223372036854775807 (maximum value for a 64-bit signed integer)
// // If `nbr` is already >= 922337203685477580 (LLONG_MAX / 10),
// // then multiplying by 10 and adding another digit could overflow.
// //
// // Cases:
// // - For positive numbers: If `nbr >= 922337203685477580` and the next digit > 7,
// // then `nbr * 10 + digit` would exceed LLONG_MAX (e.g., 9223372036854775808).
// // - For negative numbers: If `nbr >= 922337203685477580` and the next digit > 8,
// // then `nbr * 10 + digit` would exceed LLONG_MIN (e.g., -9223372036854775809).
// //
// // Why 7 and 8?
// // - LLONG_MAX = 9223372036854775807 → Last digit is 7.
// // So, if `nbr = 922337203685477580` and the next digit is > 7, overflow occurs.
// // - LLONG_MIN = -9223372036854775808 → Last digit is 8.
// // So, if `nbr = 922337203685477580` and the next digit is > 8, underflow occurs.
// if ((nbr >= 922337203685477580 && ((str[i] > 8 && n < 0) || (str[i] > 7 && n > 0))))
// {
// // Overflow: Return -1 for positive, 0 for negative (mimics INT_MAX/INT_MIN behavior)
// return ((n > 0) ? -1 : 0);
// }
// // convert digit to integer : `str[i] - '0'` converts the ASCII character to its numeric value (e.g., '5' → 5)
// nbr = nbr * 10 + (str[i] - '0');
// i++;
// }
// // apply sign and return
// return (nbr * n);
// }