0

I wants to convert String to binary(0/1 representation) and reverse.

This is my code for converting String to binary.

let String_Data: String = UI_Data.text!
let Binary_Data: Data? = String_Data.data(using: .utf8, allowLossyConversion: false)!
let String_Binary_Data = Binary_Data?.reduce("") { (acc, byte) -> String in
        acc + String(byte, radix: 2)
    }

But I do not know how to do the opposite. I would be very grateful if you could give me advice for this.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Swift's convention is for local and instance variables to use `lowerCamelCase`, and for type names to use `UpperCamelCase`. – Alexander Dec 22 '18 at 05:47

1 Answers1

1

I would start with something like this, although the performance probably isn't spectacular because it involves so many small intermediate strings.

import Foundation

extension UInt8 {
    var binaryString: String {
        return String(repeating: "0", count: self.leadingZeroBitCount) + String(self, radix: 2)
    }
}

extension Data {
    var binaryString: String {
        return self.map { $0.binaryString }.joined()
    }
}

let exampleString = "abcdefghijklmnopqrstuvwxyz"
let exampleData = exampleString.data(using: .utf8)!
print(exampleData.binaryString)
Alexander
  • 59,041
  • 12
  • 98
  • 151