11

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?

1
  • Construct a Data instance using if let strData = str.data(using: .utf8) { /* ... */ }, thereafter use the Data extension in this answer to get the data represented as a hex encoded string (let hexStr = strData.hexEncodedString()). Commented Nov 15, 2016 at 10:28

5 Answers 5

22

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()
Sign up to request clarification or add additional context in comments.

5 Comments

I've seen the explicit unwrapping (!) of str.data(using: .utf8) also use in other answers for String -> Data conversion. Do we know that data(..) method will never fail?
@dfri We know that Say Hello to My Little Friend will never fail.
Is this generally true for all non-empty String instances, or do you happen to know which kind of strings that might fail?
Even an empty string succeeds. I don't know it for sure but I guess that any human readable text is UTF8 compatible.
Yeah, it seems to be related to NULL return (see swift-corelibs-foundation/Foundation/NSString.swift for details) of CFStringCreateWithBytes(_:_:_:_:_:), a return case that is quite unspecied, "or NULL if there was a problem creating the object.". I have no idea what would yield a "problem creating the object" :)
8

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

1 Comment

Is there a way to covert it back to original string?
0

Convert your string to NSData like this.

let myString = "ABCDEF"
let data = myString.dataUsingEncoding(NSUTF8StringEncoding)

Then convert the NSData to hexadecimal string using following method -

func hexFromData(data:NSData) -> String {
    let p = UnsafePointer<UInt8>(data.bytes)
    let len = data.length
    var str: String = String()
    for i in 0...len-1 {
        str += String(format: "%02.2X", p[i])
    }
    return str
}

Hope this helped.

1 Comment

NSData is outdated in Swift 3
0

Please try this,

let string = "Say Hello to My Little Friend"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
print(data)

and its output is:

  Optional(<53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>)

Comments

-1

Swift 3

let string = "Hello World!"
let data = string.data(using: String.Encoding.utf8)

let hexString = data?.hex


extension Data {

var hex: String {
        var string = ""

        #if swift(>=3.1)
            enumerateBytes { pointer, index, _ in
                for i in index..<pointer.count {
                    string += String(format: "%02x", pointer[i])
                }
            }
        #else
            enumerateBytes { pointer, count, _ in
                for i in 0..<count {
                    string += String(format: "%02x", pointer[i])
                }
            }
        #endif

        return string
    }


}

1 Comment

Could you include some details?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.