extension Data {
//1bytes转Int
func lyz_1BytesToInt() -> Int {
var value : UInt8 = 0
let data = NSData(bytes: [UInt8](self), length: self.count)
data.getBytes(&value, length: self.count)
value = UInt8(bigEndian: value)
return Int(value)
}
//2bytes转Int
func lyz_2BytesToInt() -> Int {
var value : UInt16 = 0
let data = NSData(bytes: [UInt8](self), length: self.count)
data.getBytes(&value, length: self.count)
value = UInt16(bigEndian: value)
return Int(value)
}
//4bytes转Int
func lyz_4BytesToInt() -> Int {
var value : UInt32 = 0
let data = NSData(bytes: [UInt8](self), length: self.count)
data.getBytes(&value, length: self.count)
value = UInt32(bigEndian: value)
return Int(value)
}
}
extension Int {
// MARK:- 转成 2位byte
func lyz_to2Bytes() -> [UInt8] {
let UInt = UInt16.init(Double.init(self))
return [UInt8(truncatingIfNeeded: UInt >> 8),UInt8(truncatingIfNeeded: UInt)]
}
// MARK:- 转成 4字节的bytes
func lyz_to4Bytes() -> [UInt8] {
let UInt = UInt32.init(Double.init(self))
return [UInt8(truncatingIfNeeded: UInt >> 24),
UInt8(truncatingIfNeeded: UInt >> 16),
UInt8(truncatingIfNeeded: UInt >> 8),
UInt8(truncatingIfNeeded: UInt)]
}
// MARK:- 转成 8位 bytes
func lyz_toEightBytes() -> [UInt8] {
let UInt = UInt64.init(Double.init(self))
return [UInt8(truncatingIfNeeded: UInt >> 56),
UInt8(truncatingIfNeeded: UInt >> 48),
UInt8(truncatingIfNeeded: UInt >> 40),
UInt8(truncatingIfNeeded: UInt >> 32),
UInt8(truncatingIfNeeded: UInt >> 24),
UInt8(truncatingIfNeeded: UInt >> 16),
UInt8(truncatingIfNeeded: UInt >> 8),
UInt8(truncatingIfNeeded: UInt)]
}
}
Swift Int与Data 互转
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1、NSDictionary转NSData 2、NSData转NSDictionary 3、NSDictionar...
- 先贴上互转方法 这是Dictionary转Data 的方法 源码: func jsonToData(jsonDic...
- 方法1::string转int转byte再转ipmask最后转回int ipmask转byte转Int转strin...