最近两天在学习Swift,想着把OC里边的8583POS工具转成Swift版本。
今天做了几个转换工具
1、data转换为十六进制字符串
2、十六进制字符串转换为 data
3、十六进制字符串转为ASC码
4、ASC码转为十六进制字符串
代码如下
//
// StringPosUtilTransExtension.swift
// SwiftPOS
// Created by 刘通超 on 15/12/16.
// Copyright © 2015年刘通超. All rights reserved.
//
import Foundation
extension String{
//MARK: data 转换为十六进制字符串
/**
data 转换为十六进制字符串
<24211D34 98FF62AF> --> "24211D3498FF62AF"
- parameter data: 要转换的data
- returns: 转换后的字符串
*/
static func hexStringFromData(data data:NSData)->String{
let dataLength = data.length
let buffer = UnsafePointer<UInt8>(data.bytes)
var result = @H_301_158@ ""
for(var i=0;i<dataLength;i++){
let num = Int(buffer[i]&0xff)
result += decIntToHexString(decNum: num)
}
return result
}
//MARK: 十六 进制字符串转换为 data
/**
十六 进制字符串转换为 data
"24211D3498FF62AF" --> <24211D34 98FF62AF>
- parameter hexStr: 要转换的字符串
- returns: 转换后的data数据
*/
static func dataFromHexString(hexStr hexStr:String)->NSData{
let strLength = hexStr.utf16.count
let data = NSMutableData()
for(var index=0; index+2<=strLength; index+=2){
let subStr = hexStr.substringWithRange(Range(start: hexStr.startIndex.advancedBy(index),end: hexStr.startIndex.advancedBy(index+2)))
let dataInt = UnsafeMutablePointer<UInt32>.alloc(1)
NSScanner.init(string: subStr).scanHexInt(dataInt)
data.appendBytes(dataInt,length: 1)
}
return data
}
//MARK: hex字符串转为ASC码 00 --> 3030
/**
hex字符串转为ASC码 00 --> 3030
- parameter hexString: hex字符串
- returns: 转码后的ASC字符串
*/
static func ascStringFromHexString(hexString:String)->String{
var result = @H_301_158@ ""
let length = hexString.utf16.count
let buffer = hexString.cStringUsingEncoding(NSUTF8StringEncoding)
for(var i=0;i<length;i++){
result += decIntToHexString(decNum:Int(buffer![i]))
}
return result
}
//MARK: ASC码转为Hex字符串 3030 --> 00
/**
ASC码转为Hex字符串 3030 --> 00
- parameter ascStr: ASC字符串
- returns: 转码后的Hex字符串
*/
static func hexStringFromAscString(ascStr ascStr:String)->String{
let dda = String.dataFromHexString(hexStr: ascStr)
let result = String.init(data: dda,encoding: NSUTF8StringEncoding)
return result!
}
/**
UInt8 十进制数转为十六进制字符串(两位)
- parameter num: 十进制数字
- returns: 两位十六进制字符串
*/
private staticfunc decIntToHexString(decNum num:Int)->String{
let temp = String(format: @H_301_158@"%0x",arguments: [num])
let result = (temp.utf16.count <=1) ?@H_301_158@"0"+temp: temp;
return result
}
}
亲测可用
let strToData =String.dataFromHexString(hexStr:@H_301_158@"3132332e34353678")
let dataToStr = String.hexStringFromData(data: strToData)
let ascToHex = String.hexStringFromAscString(ascStr: dataToStr)
let hexToAsc = String.ascStringFromHexString(ascToHex)
print(@H_301_158@"strToData:\@H_301_158@(strToData@H_301_158@)")
print(@H_301_158@"dataToStr:\@H_301_158@(dataToStr@H_301_158@)")
print(@H_301_158@"hexToAsc:\@H_301_158@(hexToAsc@H_301_158@)")
print(@H_301_158@"ascToHex:\@H_301_158@(ascToHex@H_301_158@)")
strToData:<3132332e 34353678>
dataToStr:3132332e34353678
hexToAsc:3132332e34353678
ascToHex:123.456x