How to convert Data to hex string in swift

前端 未结 7 1952
走了就别回头了
走了就别回头了 2020-11-22 07:59

I want the hexadecimal representation of a Data value in Swift.

Eventually I\'d want to use it like this:

let data = Data(base64Encoded: \"aGVsbG8gd2         


        
7条回答
  •  情深已故
    2020-11-22 08:28

    This doesn't really answer the OP's question since it works on a Swift byte array, not a Data object. And it's much bigger than the other answers. But it should be more efficient since it avoids using String(format: ).

    Anyway, in the hopes someone finds this useful ...

    public class StringMisc {
    
       // MARK: - Constants
    
       // This is used by the byteArrayToHexString() method
       private static let CHexLookup : [Character] =
          [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" ]
    
    
       // Mark: - Public methods
    
       /// Method to convert a byte array into a string containing hex characters, without any
       /// additional formatting.
       public static func byteArrayToHexString(_ byteArray : [UInt8]) -> String {
    
          var stringToReturn = ""
    
          for oneByte in byteArray {
             let asInt = Int(oneByte)
             stringToReturn.append(StringMisc.CHexLookup[asInt >> 4])
             stringToReturn.append(StringMisc.CHexLookup[asInt & 0x0f])
          }
          return stringToReturn
       }
    }
    

    Test case:

      // Test the byteArrayToHexString() method
      let byteArray : [UInt8] = [ 0x25, 0x99, 0xf3 ]
      assert(StringMisc.byteArrayToHexString(byteArray) == "2599F3")
    

提交回复
热议问题