10

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
  • 274,689
  • 30
  • 353
  • 361
Usman Javed
  • 2,437
  • 1
  • 17
  • 26
  • Construct a `Data` instance using `if let strData = str.data(using: .utf8) { /* ... */ }`, thereafter use the `Data` extension in [this answer](http://stackoverflow.com/a/40089462/4573247) to get the data represented as a hex encoded string (`let hexStr = strData.hexEncodedString()`). – dfrib Nov 15 '16 at 10:28

5 Answers5

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()
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 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? – dfrib Nov 15 '16 at 10:39
  • 1
    @dfri We know that *Say Hello to My Little Friend* will never fail. – vadian Nov 15 '16 at 10:40
  • Is this generally true for all non-empty `String` instances, or do you happen to know which kind of strings that might fail? – dfrib Nov 15 '16 at 10:47
  • Even an empty string succeeds. I don't know it for sure but I guess that any human readable text is UTF8 compatible. – vadian Nov 15 '16 at 10:52
  • Yeah, it seems to be related to `NULL` return (see [swift-corelibs-foundation/Foundation/NSString.swift](https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSString.swift#L1185) for details) of [`CFStringCreateWithBytes(_:_:_:_:_:)`](https://developer.apple.com/reference/corefoundation/1543419-cfstringcreatewithbytes?language=obj_1), 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"_ :) – dfrib Nov 15 '16 at 12:32
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
Vasily Bodnarchuk
  • 24,482
  • 9
  • 132
  • 127
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.

sudhanshu-shishodia
  • 1,100
  • 1
  • 11
  • 25
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>)
-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
    }


}
Rakesh Gujari
  • 899
  • 1
  • 8
  • 12