Skip to content

Commit

Permalink
Adds Data(hex:) to allow creating Data from hex-Strings (without pref…
Browse files Browse the repository at this point in the history
…ix) (#35)
  • Loading branch information
melle committed Jul 6, 2022
1 parent 34cba24 commit 503d411
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Sources/FoundationExtensions/Data/Data+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,25 @@ extension Numeric {
}
}

extension Data {

public init?(hex: String) {
let length = hex.count / 2
var data = Data(capacity: length)
for i in 0 ..< length {
let j = hex.index(hex.startIndex, offsetBy: i * 2)
let k = hex.index(j, offsetBy: 2)
let bytes = hex[j..<k]
if var byte = UInt8(bytes, radix: 16) {
data.append(&byte, count: 1)
} else {
return nil
}
}
self = data
}
}

extension Data {

public func range(start: Int, length: Int) -> Data {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,14 @@ class DataExtensionsTests: XCTestCase {
let partialData = fullData.range(start: 4, length: 1)
XCTAssertEqual(partialData, Data([]))
}

func testDataFromHexString() {
let sut = Data(hex: "6949efc9cf1a68a772af811bca5250bb744aac7c")!
XCTAssertEqual(sut, Data([0x69, 0x49, 0xef, 0xc9,
0xcf, 0x1a, 0x68, 0xa7,
0x72, 0xaf, 0x81, 0x1b,
0xca, 0x52, 0x50, 0xbb,
0x74, 0x4a, 0xac, 0x7c]))
}
}
#endif

0 comments on commit 503d411

Please sign in to comment.