0

I have converted the string "UK" into hex using code below. How can I convert it to hex?

    let str = auxText
    let bytes = str.utf8
    var buffer = [UInt8](bytes)
    buffer[0] = buffer[0] + UInt8(1)
    print("ascii value is",buffer)
halfer
  • 19,824
  • 17
  • 99
  • 186
shivadeep
  • 68
  • 1
  • 11
  • possible duplicate https://stackoverflow.com/questions/24229505/how-to-convert-an-int-to-hex-string-in-swift – Bilal Jun 16 '17 at 07:36
  • Similar question can be found in [Swift2](https://stackoverflow.com/questions/32884783/swift-2-how-to-encode-from-ascii-to-hexadecimal) and [Linux](https://stackoverflow.com/questions/36441684/convert-ascii-to-hex-and-back-in-swift-for-linux) research, take a look and try. Then you can avoid to be marked as duplicate. – Marcel T Jun 16 '17 at 07:37
  • not working.My ascii value is [85,75],i am not getting desired value – shivadeep Jun 16 '17 at 07:45
  • 1
    What *hex* form do you expect? – vadian Jun 16 '17 at 07:58

1 Answers1

1

In Swift 4, you can convert your ascii encoded string to data with

string.data(using: .ascii)

To convert the data to hex or decimal you can use the following extensions:

extension Data {

    var hexString: String {
        return map { String(format: "%02hhx", $0) }.joined()
    }

    var decimalString: String {
        return map { String(format: "%d", $0) }.joined()
    }

}

Your test string "UK"

let string = "UK"

Evaluates with

let hexString = string.data(using: .ascii)!.hexString

To

554b

And with

let decimalString = string.data(using: .ascii)!.decimalString

To

8575

Both results are correct, you can look them up in any ASCII table.

sundance
  • 2,930
  • 1
  • 20
  • 25