Swift3.0 进制转换

  Swift3.0 进制转换

  模块可以直接使用,写的不是很好,欢迎来喷

// Data -> HexStrings

func dataToHexStringArrayWithData(data: NSData) -> [String] {

let byteArray:[Int] = DataToIntWithData(data: data)

var byteStrings: [String] = []

for (_,value) in byteArray.enumerated() {

byteStrings.append(ToHex(tmpid: value))

}

return byteStrings

}

// HexString -> Data

func hexToBytes(bytesStr: String) -> Data? {

var data = Data(capacity: bytesStr.characters.count / 2)

let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)

regex.enumerateMatches(in: bytesStr, options: [], range: NSMakeRange(0, bytesStr.characters.count)) { match, flags, stop in

let byteString = (bytesStr as NSString).substring(with: match!.range)

var num = UInt8(byteString, radix: 16)!

data.append(&num, count: 1)

}

guard data.count > 0 else {

return nil

}

return data

}

// Data -> 10

func DataToIntWithData(data: NSData) -> [Int] {

var byteArray:[Int] = []

for i in 0..<data.length {

var temp:Int = 0

data.getBytes(&temp, range: NSRange(location: i,length:1 ))

byteArray.append(temp)

}

return byteArray

}

// 10 -> 16

func ToHex(tmpid: Int) -> String {

let leftInt: Int  = tmpid / 16

let rightInt: Int = tmpid % 16

var leftIndex: String = ""

var rightIndex: String = ""

let numberArray = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]

for i in 0..<numberArray.count {

if i == leftInt {

leftIndex = numberArray[i]

}

if i == rightInt {

rightIndex = numberArray[i]

}

}

return "\(leftIndex)\(rightIndex)"

}

// 16 -> 10

func ToInt(hexString: String) -> Int {

var _hexString = hexString

// 转小写

_hexString = _hexString.lowercased()

// 拆分字符串 转成10进制 计算

var term = 0

let intArray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];

let _hex = NSString(string: _hexString)

let left = String(format: "%c", _hex.character(at: 0))

let right = String(format: "%c", _hex.character(at: 1))

var leftValue = 0

var rightValue = 0

for (index,value) in intArray.enumerated() {

if left == value {

leftValue = index

}

if right == value {

rightValue = index

}

}

term = leftValue * 16 + rightValue

return term;

}

-----------------这里是分割线,后续更新---------------------------------

上一篇:mysql数据库-定义函数-存储过程写法


下一篇:SQL Server 2008 允许远程链接 解决方法