1、核心程序实现
class CRC16{
static let instance = CRC16()
static func getCRC(arr:[Int]) -> Int{
var CRC:Int = 0x0000ffff
let POLYNOMIAL:Int = 0x0000a001
let length = arr.count
for i in 0..>= 1
CRC ^= POLYNOMIAL
}else{
CRC >>= 1
}
}
}
return CRC
}
}
2、重载方法运行程序
override func viewDidLoad() {
super.viewDidLoad()
let a:String = "&T1 "
//此数组为存放字符串的ascii码值
var arr:[Int]=[]
or i in a.indices{
//把字符串转化为ascii码,然后重新放到一个数组内部
arr.append(a[i].ascii)
}
print(CRC16.getCRC(arr:arr))
}
3、扩展方法
//String扩展
extension String{
//subscript函数可以检索数组中的值
//直接按照索引方式截取制定索引的字符
subscript(_ i:Int) -> Character{
//读取字符
get{
return self[index(startIndex,offsetBy: i)]
}
//修改字符
set{
//转化为字符数组
var arr:[Character] = Array(self)
arr[i] = newValue
self = String(arr)
}
}
//String转ASCII整数值(定义小写为整数值)
public var ascii:Int{
return Int(self.unicodeScalars.first?.value ?? 0)
}
}
//Character扩展
extension Character{
//Character转ASCII整数值(定义小写整数值)
var ascii:Int{
get{
return Int(self.unicodeScalars.first?.value ?? 0)
}
}
}
//Int转Character,ascii值(定义大写为字符值)
extension Int{
var ASCII:Character{
get{return Character(UnicodeScalar(self)!)}
}
}