lnlink

iOS app for connecting to lightning nodes
git clone git://jb55.com/lnlink
Log | Files | Refs | Submodules | README | LICENSE

Hex.swift (1375B)


      1 //
      2 //  Hex.swift
      3 //  lightninglink
      4 //
      5 //  Created by William Casarin on 2022-08-09.
      6 //
      7 
      8 import Foundation
      9 
     10 func hexchar(_ val: UInt8) -> UInt8 {
     11     if val < 10 {
     12         return 48 + val;
     13     }
     14     if val < 16 {
     15         return 97 + val - 10;
     16     }
     17     assertionFailure("impossiburu")
     18     return 0
     19 }
     20 
     21 
     22 func hex_encode(_ data: [UInt8]) -> String {
     23     var str = ""
     24     for c in data {
     25         let c1 = hexchar(c >> 4)
     26         let c2 = hexchar(c & 0xF)
     27 
     28         str.append(Character(Unicode.Scalar(c1)))
     29         str.append(Character(Unicode.Scalar(c2)))
     30     }
     31     return str
     32 }
     33 
     34 
     35 func char_to_hex(_ c: UInt8) -> UInt8?
     36 {
     37     // 0 && 9
     38     if (c >= 48 && c <= 57) {
     39         return c - 48 // 0
     40     }
     41     // a && f
     42     if (c >= 97 && c <= 102) {
     43         return c - 97 + 10;
     44     }
     45     // A && F
     46     if (c >= 65 && c <= 70) {
     47         return c - 65 + 10;
     48     }
     49     return nil;
     50 }
     51 
     52 
     53 func hex_decode(_ str: String) -> [UInt8]?
     54 {
     55     if str.count == 0 {
     56         return nil
     57     }
     58     var ret: [UInt8] = []
     59     let chars = Array(str.utf8)
     60     var i: Int = 0
     61     for c in zip(chars, chars[1...]) {
     62         i += 1
     63 
     64         if i % 2 == 0 {
     65             continue
     66         }
     67 
     68         guard let c1 = char_to_hex(c.0) else {
     69             return nil
     70         }
     71 
     72         guard let c2 = char_to_hex(c.1) else {
     73             return nil
     74         }
     75 
     76         ret.append((c1 << 4) | c2)
     77     }
     78 
     79     return ret
     80 }
     81