 //
 func convertHexToBase64(input: String) throws -> String {
 
+    var result = ""
+
     // an empty input string produces an empty Base64 string
     guard !input.isEmpty else {
-        return ""
+        return result
     }
 
-    let bytes = try? convertHexToBytes(input)
+    // convert input string to byte array
+    let bytes = try! convertHexToBytes(input)
 
-    var result = ""
+    // for each 3-byte segment, map to 4 Base64 characters
+    for i in 0...(bytes.count / 3 - 1) {
+        var index = bytes[i*3] >> 2
+        result += String(base64[index])
+        index = ((bytes[i*3] & 0x03) << 4) | (bytes[i*3+1] >> 4)
+        result += String(base64[index])
+        index = ((bytes[i*3+1] & 0x0F) << 2) | ((bytes[i*3+2] & 0xC0) >> 6)
+        result += String(base64[index])
+        index = bytes[i*3+2] & 0x3F
+        result += String(base64[index])
+    }
 
-    // for each 6-bit chunk
-
-        // map 6-bit chunk to Base64 index table
-
-        // add encoded character to result
+    // pad output with trailing "=" characters
 
     return result
 }


    // for this unit test, the input is valid so we don't have to catch the exception
    let result = try! convertHexToBase64(input)

    return (result == output)
}

// Constants used throughout this file
//
let hex = "0123456789abcdef"
let base64 = [Character]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".characters)

//
// Exception types
