An advanced Ethereum/EVM mobile wallet
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
alpha-wallet-ios/Trust/Extensions/Data.swift

59 lines
1.5 KiB

// Copyright SIX DAY LLC. All rights reserved.
import Foundation
extension Data {
var hex: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var hexEncoded: String {
return "0x" + self.hex
}
init(hex: String) {
let len = hex.count / 2
var data = Data(capacity: len)
for i in 0..<len {
let j = i*2
let bytes = hex[j..<j+2]
if var num = UInt8(bytes, radix: 16) {
data.append(&num, count: 1)
}
}
self = data
}
init?(fromHexEncodedString string: String) {
// Convert 0 ... 9, a ... f, A ...F to their decimal value,
// return nil for all other input characters
func decodeNibble(u: UInt16) -> UInt8? {
switch u {
case 0x30 ... 0x39:
return UInt8(u - 0x30)
case 0x41 ... 0x46:
return UInt8(u - 0x41 + 10)
case 0x61 ... 0x66:
return UInt8(u - 0x61 + 10)
default:
return nil
}
}
self.init(capacity: string.utf16.count/2)
var even = true
var byte: UInt8 = 0
for c in string.utf16 {
guard let val = decodeNibble(u: c) else { return nil }
if even {
byte = val << 4
} else {
byte += val
self.append(byte)
}
even = !even
}
guard even else { return nil }
}
}