Swift3 convert string value to hexadecimal string
15,233
Solution 1
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()
Solution 2
Details
- Xcode 11.2.1 (11B500), Swift 5.1
Solution
extension String {
func toHexEncodedString(uppercase: Bool = true, prefix: String = "", separator: String = "") -> String {
return unicodeScalars.map { prefix + .init($0.value, radix: 16, uppercase: uppercase) } .joined(separator: separator)
}
}
Usage
let str = "Hello, playground"
print(str.toHexEncodedString()) // 48656C6C6F2C20706C617967726F756E64
print(str.toHexEncodedString(uppercase: false, prefix: "0x", separator: " ")) // 0x48 0x65 0x6c 0x6c 0x6f 0x2c 0x20 0x70 0x6c 0x61 0x79 0x67 0x72 0x6f 0x75 0x6e 0x64
Related videos on Youtube
Author by
Usman Javed
Contact me on LinkedIn : https://www.linkedin.com/in/usman-javaid-89129339/ Email me : [email protected] "I think if you do something and it turns out pretty good, then you should go do something else wonderful, not dwell on it for too long. Just figure out what’s next." by Steve Jobs
Updated on September 14, 2022Comments
-
Usman Javed over 1 year
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?
-
vadian over 7 years
NSData
is outdated in Swift 3 -
dfrib over 7 yearsI've seen the explicit unwrapping (
!
) ofstr.data(using: .utf8)
also use in other answers forString
->Data
conversion. Do we know thatdata(..)
method will never fail? -
vadian over 7 years@dfri We know that Say Hello to My Little Friend will never fail.
-
dfrib over 7 yearsIs this generally true for all non-empty
String
instances, or do you happen to know which kind of strings that might fail? -
vadian over 7 yearsEven an empty string succeeds. I don't know it for sure but I guess that any human readable text is UTF8 compatible.
-
dfrib over 7 yearsYeah, it seems to be related to
NULL
return (see swift-corelibs-foundation/Foundation/NSString.swift for details) ofCFStringCreateWithBytes(_:_:_:_:_:)
, a return case that is quite unspecied, "orNULL
if there was a problem creating the object.". I have no idea what would yield a "problem creating the object" :) -
jhhoff02 over 6 yearsCould you include some details?