Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift3 convert string value to hexadecimal string

Tags:

xcode

ios

swift3

I am new to Swift and I want to convert a string into hexadecimal string. I have found a Objective-C function to a string into hexadecimal.

NSString * str = @"Say Hello to My Little Friend";

NSString * hexString = [NSString stringWithFormat:@"%@",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
                                         length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];

for (NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
    hexString = [hexString stringByReplacingOccurrencesOfString:toRemove withString:@""];

NSLog(@"hexStr:%@", hexString);

Now I am unable to convert this function in Swift. Currently I am using Swift3.

Please someone can do this for me?

like image 464
Usman Javed Avatar asked Nov 28 '22 22:11

Usman Javed


1 Answers

This produces the same output as the ObjC version

let str = "Say Hello to My Little Friend"
let data = Data(str.utf8)
let hexString = data.map{ String(format:"%02x", $0) }.joined()
like image 193
vadian Avatar answered Dec 20 '22 23:12

vadian