FreeCalypso > hg > freecalypso-tools
comparison miscutil/make-imeisv.c @ 744:2dcfad8a3ed0
make-imeisv utility written
| author | Mychaela Falconia <falcon@freecalypso.org> |
|---|---|
| date | Mon, 19 Oct 2020 06:35:35 +0000 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 743:88a1c8af39ac | 744:2dcfad8a3ed0 |
|---|---|
| 1 /* | |
| 2 * This utility constructs a 16-digit IMEISV from a 15-digit IMEI | |
| 3 * (which must have a valid Luhn check digit) and a 2-digit SV field. | |
| 4 * It is intended for use in shell scripts. | |
| 5 */ | |
| 6 | |
| 7 #include <stdio.h> | |
| 8 #include <ctype.h> | |
| 9 #include <stdlib.h> | |
| 10 | |
| 11 parse_imei_arg(input, buf) | |
| 12 char *input, *buf; | |
| 13 { | |
| 14 char *cp; | |
| 15 int i; | |
| 16 | |
| 17 cp = input; | |
| 18 if (!isdigit(*cp)) { | |
| 19 inv: fprintf(stderr, | |
| 20 "error: IMEI argument must have 15 decimal digits\n"); | |
| 21 exit(1); | |
| 22 } | |
| 23 for (i = 0; i < 15; i++) { | |
| 24 if (ispunct(*cp)) | |
| 25 cp++; | |
| 26 if (!isdigit(*cp)) | |
| 27 goto inv; | |
| 28 buf[i] = *cp++; | |
| 29 } | |
| 30 if (*cp) | |
| 31 goto inv; | |
| 32 } | |
| 33 | |
| 34 check_luhn(digits) | |
| 35 char *digits; | |
| 36 { | |
| 37 int i, dig, sum; | |
| 38 | |
| 39 sum = 0; | |
| 40 for (i = 0; i < 14; i++) { | |
| 41 dig = digits[i] - '0'; | |
| 42 if (i & 1) { | |
| 43 dig *= 2; | |
| 44 if (dig > 9) | |
| 45 dig -= 9; | |
| 46 } | |
| 47 sum += dig; | |
| 48 } | |
| 49 dig = sum % 10; | |
| 50 if (dig) | |
| 51 dig = 10 - dig; | |
| 52 if (digits[14] != dig + '0') { | |
| 53 fprintf(stderr, "error: given IMEI fails Luhn check\n"); | |
| 54 exit(1); | |
| 55 } | |
| 56 } | |
| 57 | |
| 58 main(argc, argv) | |
| 59 char **argv; | |
| 60 { | |
| 61 char imeibuf[15]; | |
| 62 | |
| 63 if (argc != 3) { | |
| 64 fprintf(stderr, "usage: %s IMEI SV\n", argv[0]); | |
| 65 exit(1); | |
| 66 } | |
| 67 parse_imei_arg(argv[1], imeibuf); | |
| 68 check_luhn(imeibuf); | |
| 69 if (!isdigit(argv[2][0]) || !isdigit(argv[2][1]) || argv[2][2]) { | |
| 70 fprintf(stderr, | |
| 71 "error: SV argument must have 2 decimal digits\n"); | |
| 72 exit(1); | |
| 73 } | |
| 74 printf("%.8s-%.6s-%s\n", imeibuf, imeibuf + 8, argv[2]); | |
| 75 exit(0); | |
| 76 } |
