我想为所有整数类型创建一个Integer-to-Hex函数.
对于1字节的Int8,它返回两个字母,例如0A
对于2字节的Int16,它返回四个字母,例如0A0B
对于8位Int64,它返回16个字母,例如0102030405060708
func hex(v: Int) -> String { var s = "" var i = v for _ in 0..<sizeof(Int)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s } func hex(v: Int64) -> String { var s = "" var i = v for _ in 0..<sizeof(Int64)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s } func hex(v: Int32) -> String { var s = "" var i = v for _ in 0..<sizeof(Int32)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s } func hex(v: Int16) -> String { var s = "" var i = v for _ in 0..<sizeof(Int16)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s } func hex(v: Int8) -> String { var s = "" var i = v for _ in 0..<sizeof(Int8)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s }
上面的代码工作正常.
然后我尝试创建一个通用版本,如下所示:
func hex<T: IntegerType>(v: T) -> String { var s = "" var i = v for _ in 0..<sizeof(T)*2 { s = String(format: "%x",i & 0xF) + s i = i >> 4 } return s }
什么是正确的方式来实现这个任务?
非常简单的解决方案是将输入值合并到.toIntMax()中的IntMax中:
原文链接:https://www.f2er.com/swift/318816.htmlfunc hex<T: IntegerType>(v: T) -> String { var s = "" var i = v.toIntMax() for _ in 0..<sizeof(T)*2 { s = String(format: "%x",i & 0xF) + s i >>= 4 } return s }
注意:这仅适用于0 … Int64.max值.
但是,我会这样做:
func hex<T: IntegerType>(v: T) -> String { return String(format:"%0\(sizeof(T) * 2)x",v.toIntMax()) }
注意:这只适用于0 … UInt32.max值.
已添加:这适用于所有可用的整数类型/值.
func hex<T:IntegerType>(var v:T) -> String { var s = "" for _ in 0..<sizeof(T) * 2 { s = String(format: "%X",(v & 0xf).toIntMax()) + s v /= 16 } return s }
> .toIntMax()将T转换为具体的整数类型.> / 16而不是>> 4.