Quantcast
Channel: Verdana Experiments » JavaScript
Viewing all articles
Browse latest Browse all 3

EAN-13 条形码末位校验码计算

$
0
0

具体的计算步骤:

  1. 12 位数字从左至右,分别计算奇数位以及偶数位之和
  2. 求奇数位之和
  3. 求偶数位之和,结果乘以 3
  4. 第 2、3 步,2 个计算结果相加
  5. 第 4 步的结果取个位数,用 10 减去个位数得到的数字,即是校验码
  6. 第 5 步个位数为 0 的话,校验码也是 0

下面是用 MooTools 实现的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * EAN-13 條形碼生成
 *
 * num_system: 国家代码(3位)
 * manufacturer_code: 厂商代码(4位)
 * product_code: 产品代码(5位)
 */
var BarCode = new Class({
    // 初始化
    initialize: function(num_system, manufacturer_code, product_code)
    {
        // 转换为字符串
        num_system          = num_system.toString();
        manufacturer_code   = manufacturer_code.toString();
        product_code        = product_code.toString();
 
        // 得到前 12 位条形码
        this.number = num_system + manufacturer_code + product_code;
    },
 
    // 生成校验码
    checkDigit: function()
    {
        // 将 12 位数字的字符串,拆成数组
        var numbers = $A(this.number.split(''));
 
        var s1 = 0; // 奇数位之和
        var s2 = 0; // 偶数位之和
        var s3 = 0; // (s1 + s2 * 3) 取个位数
 
        // 遍历数组开始求和
        numbers.each(function(num, index) {
            num = num.toInt();
 
            if (index%2 == 0) {
                // 奇数位
                s1 += num;
            } else {
                // 偶数位
                s2 += num;
            }
        });
 
        s3 = (s1 + s2 * 3) % 10;
 
        // 最终的校验码
        this.digit_code = ( s3 > 0) ? 10 - s3 : 0;
    },
 
    // 输出最终的 EAN-13 条形码
    output: function()
    {
        // 计算末位校验码
        this.checkDigit();
 
        // 输出条形码
        return this.number.toString() + this.digit_code.toString();
    }
});
 
// 示例,生成一个台湾 (471) 的商品条码
var mycode = new BarCode(471, 1314, 52101).output();

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images