All I am looking to do is take a string and get its hex value. I've been following this post. Here is the code I have in my playground:
let str = "Say Hello to My Little Friend" let data = str.data(using: String.Encoding.utf16) print("\(data!)")
However, my code just prints:
"60 bytes\n"
How can I print the hex value? For reference, it should be:
5361792048656c6c6f20746f204d79204c6974746c6520467269656e64
In Swift, you can print a variable or a constant to the screen using the print() function.
Swift – Print without New Line To print to console output without a new line as trailing character using print() statement, pass empty string for the parameter terminator .
To create a String variable in Swift, declare the variable as String, or assign empty string to the variable, or assign new String instance to the variable.
Since Data
is a Sequence of UInt8, you could map each byte to a string and then join them:
data.map { String(format: "%02x", $0) }.joined()
Just
print(data! as NSData)
PS: Your expected hex is .utf8
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