首页 > 技术技巧 > 用shell升级15位身份证到18位

用shell升级15位身份证到18位

2009年8月20日 wgzhao 发表评论 阅读评论

写着好玩写的,纯粹是想知道最后那个校验码是怎么算出来的,具体的算法可以参考这里

更详细的例子,可以参考下面的链接:

http://www.heybrain.com/notheal/article/1138.html

我这里是用shell实现了,其实用C实现应该是最好的,毕竟算法的东西,C还是要快很多,我本是打算用C的,结果发现我都忘记得差不多了,连最简单的申明数组并初始化都忘记了,于是只要用效率比较低的shell,不过在做一些匹配和校验的时候,感觉比C要方便一些,不多说了,给代码

#!/bin/bash
#Description: Convert your 15bit old ID card into 18bit ID Card
#Author: mlsx mlsx.xplore(at) gmail.com
#Blog: http://mlsx.xplore.cn

crc=( 1 0 X 9 8 7 6 5 4 3 2 ) #CRC bit
weight=( 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 ) #weight factor
oldcard=${1:-123}
while true
do
  echo $oldcard |egrep -q "^[0-9]{15}$"
  [ $? -eq 0 ] && break
  echo -n "Pls hit your 15bit old ID card:"
  read oldcard
done

#insert two number "19" after sixth
tmpcard="`echo ${oldcard:0:6}`19`echo ${oldcard:6}`"

#split tmpcard into single digtial
y=0
for i in `echo {0..16}`
do
  a=${tmpcard:$i:1}
  (( y += $a * ${weight[$i]} ))
done

crcindex=`expr $y % 11`

echo "Your New 18bit ID Card is : ${tmpcard}${crc[$crcindex]}"

exit 0

一个实际的例子如下:

$ idcard.sh 340524800101001
Your New 18bit ID Card is : 34052419800101001X

原创文章,转载请注明: 转载自Linux|系统管理|WEB开发

本文链接地址: 用shell升级15位身份证到18位

分类: 技术技巧 标签: , ,
  1. 2009年8月20日20:15 | #1

    第11行 echo $oldcard |egrep -q “^[0-9]{15}$”的egrep换成grep也许会好些,我最开始用grep不成功,原来{和}符号都需要转义(escaped)

    echo $oldcard |grep -q “^[0-9]\{15\}$”

    回复回复
  1. 本文目前尚无任何 trackbacks 和 pingbacks.