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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With