15 分(;´Д`)
こないだの ローレイヤー勉強会 - xcorp::When it rains, it pours. の懇親会でローレイヤー研究家のかないさんが「入社試験の時にその場でコード書いてもらったりするよ。…atoi とか」とかなんとか言ってたのをウンコしてるときにふと思い出したので書いてみるプレイ。これしきのことに 15 分もかかるとは…。老いたな…トキ…(何
#include <stdio.h> #include <ctype.h> int atoi(const char *src) { int flag = 0, val = 0; const char *s = src; while (isspace(*s) != 0) { s++; } if (*s == '-') { flag = 1; s++; } else if (*s == '+') { s++; } while (isdigit(*s) != 0) { val = val * 10 + (*s - '0'); s++; } return (flag == 0) ? val : -val; } int main(void) { printf("1024: %d\n", atoi("1024")); printf("-1024768: %d\n", atoi("-1024768")); printf("-1: %d\n", atoi("-1")); printf("4294967296: %d\n", atoi("4294967296")); printf("4294967295: %d\n", atoi("4294967295")); printf("2147483648: %d\n", atoi("2147483648")); printf("2147483647: %d\n", atoi("2147483647")); printf("1024abc256: %d\n", atoi("1024abc256")); printf("1-24abc256: %d\n", atoi("1-24abc256")); printf("--1-24abc6: %d\n", atoi("--1-24abc6")); return 0; }
コンパイルして実行。
[xcorp@volatile ~]$ cc -o atoi atoi.c [xcorp@volatile ~]$ ./atoi 1024: 1024 -1024768: -1024768 -1: -1 4294967296: 0 4294967295: -1 2147483648: -2147483648 2147483647: 2147483647 1024abc256: 1024 1-24abc256: 1 --1-24abc6: 0
ホンモノの atoi はどーだったかね、ってことでテストコードも。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main(void) { printf("1024: %d\n", atoi("1024")); printf("-1024768: %d\n", atoi("-1024768")); printf("-1: %d\n", atoi("-1")); printf("4294967296: %d\n", atoi("4294967296")); printf("4294967295: %d\n", atoi("4294967295")); printf("2147483648: %d\n", atoi("2147483648")); printf("2147483647: %d\n", atoi("2147483647")); printf("1024abc256: %d\n", atoi("1024abc256")); printf("1-24abc256: %d\n", atoi("1-24abc256")); printf("--1-24abc6: %d\n", atoi("--1-24abc6")); return 0; }
同様にコンパイルして実行。なんか違う(;´Д`)
[xcorp@volatile ~]$ cc -o atoi2 atoi2.c [xcorp@volatile ~]$ ./atoi2 1024: 1024 -1024768: -1024768 -1: -1 4294967296: 2147483647 4294967295: 2147483647 2147483648: 2147483647 2147483647: 2147483647 1024abc256: 1024 1-24abc256: 1 --1-24abc6: 0
先頭ビット落としてやがる。ぎゃふん!!