I have used this md5 and I get the hashed result. However, the return is like this: <8f833933 03a151ea 33bf6e3e bbc28594>
. Am new to swift so am not entirely sure whether it's an encapsulation. How do I get rid of the less and greater than sign?
Asked
Active
Viewed 236 times
0
-
That means that the NSData object is printed using its `description` method. If you search for "NSData to hex string" then you should find some solutions (for example: http://stackoverflow.com/a/29642198/1187415). – Martin R Sep 26 '15 at 07:02
1 Answers
0
As you can see from the signature, the function returns a NSData object:
func md5(#string: String) -> NSData
If you want to convert it to a string, you’ll need to encode it in a human-readable format. The most common is a hexadecimal representation.
If you use the newer Swift 2 function from that question, which returns a UInt8 array
func md5(string string: String) -> [UInt8] {
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_MD5(data.bytes, CC_LONG(data.length), &digest)
}
return digest
}
you could use this handy toHex
function:
func toHex(bytes: [UInt8]) -> String {
var numbers = [String]()
for byte in bytes {
if byte < 0x10 {
numbers.append("0")
}
numbers.append(String(byte, radix: 16, uppercase: true))
}
return numbers.joinWithSeparator("")
}
Then this returns a string:
toHex(md5("Hello"))
(In my opinion you should always prefer pure Swift types (array of UInt8) over Foundation types (NSData).)

idmean
- 14,540
- 9
- 54
- 83
-
@user3813647 If this answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – idmean Dec 16 '15 at 13:25