Last active
August 29, 2015 14:25
-
-
Save ochaochaocha3/eccc69c995f2af2e11fa to your computer and use it in GitHub Desktop.
バーコード(JAN)のチェックディジットを算出する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <assert.h> | |
// チェックディジットを返す | |
// [data] チェックディジットなしのデータ | |
// [length] データの長さ | |
int check_digit(char* data, int length) { | |
int sum_odd = 0; // 奇数の和 | |
int sum_even = 0; // 偶数の和 | |
int mod10; // 10 で割った余り | |
int i; | |
for (i = length - 1; i >= 0; i -= 2) { | |
sum_odd += data[i] - '0'; | |
} | |
for (i = length - 2; i >= 0; i -= 2) { | |
sum_even += data[i] - '0'; | |
} | |
mod10 = (3 * sum_odd + sum_even) % 10; | |
return (mod10 == 0) ? 0 : (10 - mod10); | |
} | |
int main(void) { | |
char data1[] = "4912345"; | |
char data2[] = "1900001"; | |
char data3[] = "1900002"; | |
int cd1 = check_digit(data1, strlen(data1)); | |
int cd2 = check_digit(data2, strlen(data2)); | |
int cd3 = check_digit(data3, strlen(data3)); | |
assert(cd1 == 6); | |
printf("Check digit for %s is %d\n", data1, cd1); | |
assert(cd2 == 5); | |
printf("Check digit for %s is %d\n", data2, cd2); | |
assert(cd3 == 2); | |
printf("Check digit for %s is %d\n", data3, cd3); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment