Erosion
Erosion

Reputation: 31

Convert ASCII to HEX and back in Swift for Linux

I am fairly new to Swift but I have been programming in Java for over a year. I wanted to try Swift but I don't have a Mac so instead I use Linux and the open sourced Swift packages. This is great but I get a huge amount of errors and it seems like most common fixes or implementations do not work on the Ubuntu OS.

Using Atom, I have a program that needs to convert normal ASCII strings into hexadecimal code, and then back to the respective ASCII text. I have managed to get it to hexadecimal using this code:

str = str.utf8.map{ $0 }.reduce("") {
        $0 + String($1, radix: 16, uppercase: false)
     }

I got this off of another question here. And I would love to comment and ask how to go back, but I'm new to Stack Overflow and I need 50 reputation to comment anything. :/

I've tried a method implemented here, but I got the following error in Atom:

/home/xxx/xxx/main.swift:15:20: error: cannot convert value of type 'String' to type 'NSSTring' in coercion
let nsString = hexString as NSString
               ^~~~~~~~~

So, I kept searching and found this post. The OP's version gave me about 8 errors and then I tried @Shripada's version and Atom gave me this error:

/home/xxx/xxx/main.swift:36:20: error: 'stride(from:to:by:)' is unavailable: call the 'stride(to:by:)' method instead
let numbers = stride(from: 0, to:chars.count, by: 2).map{
              ^~~~~~

So I tried stride(to:by:)...

/home/xxx/xxx/main.swift:36:20: error: cannot invoke 'stride' with argument list of type '(to: Int, by: Int)'

As of now, I have searched through many posts here and I still cannot find a single solution... Any help is much appreciated and thank you.

Upvotes: 1

Views: 516

Answers (1)

Karl Weinmeister
Karl Weinmeister

Reputation: 497

I combined and slightly modified the samples you provided, and it's now working. You can access the code and run it on the IBM Swift Sandbox here:

//Input text
var text = "Hello"
print("Text: " + text)

// Convert from text -> hex
let hex = text.utf8.map{ $0 }.reduce("") {
  $0 + String($1, radix: 16, uppercase: false)
}
print("Hex: " + hex)

//Convert from hex -> text
text = ""
let chars = Array(hex.characters)
let numbers = stride(from: 0, to: chars.count, by: 2).map() {
  let twoChars = String(chars[$0 ..< min($0 + 2, chars.count)])
  text.append(String(describing: UnicodeScalar(Int(twoChars, radix: 16)!)!))
}

print("Text: " + text)

Upvotes: 1

Related Questions