Converting Binary String back to original string using Swift

I have one module that is supposed to encode a string to binary and another module that, when passed the encoded binary string, is supposed to to decode that string and print the original string.

In my first module file, I have the encoding process that works. I can pass a regular string of text and the module returns the Binary version of that string, here is the code:
Code Block
// Returns the byte array value after string value is appended to the resulting string array.
func binaryStringArray(array:[UInt8]) -> [String] {
    var res:[String] = []
    // Byte in byte array -> append to byte2Binary($e)
    for e in array {
        let bin = byte2Binary(byte: e)
        res.append(bin)
    }
    // Return the array - raw array print
    return res;
}
// Converter - string byte to binary
func byte2Binary(byte:UInt8) -> String {
    var result = String(byte, radix: 2)
    while result.count < 8 {
        result = "0" + result
    }
    return result;
}
var str:String = "test string"
var bytes:[UInt8] = []
// Iterate through the string characters
for char in str.utf8 {
//
    bytes += [char]
}
// Iterate through the data string array and print the contents of that array
for value in binaryStringArray(array: bytes) {
    print(value)
}
// Result output: 01110100 01100101 01110011 01110100 00100000 01110011 01110100 01110010 01101001 01101110 01100111

What I want to do is take the "Result output" pass it as a string in file 2 (decoder) and decode that binary string back to its original string form ("test string").
Answered by OOPer in 633466022
You can make the Result output back to the bytes, then to the original string.

With your code, the Result output contains line break characters at each end of the binary string, so I used this String as Result outpuut.
Code Block
let resultOutput = """
01110100
01100101
01110011
01110100
00100000
01110011
01110100
01110010
01101001
01101110
01100111
"""


Using resultOutput, you can write something like this:
Code Block
//Convert the Result output back to the bytes
let byteArray = resultOutput.components(separatedBy: .whitespacesAndNewlines)
.compactMap {UInt8($0, radix: 2)}
//print(byteArray)
//->[116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 103]
//Construct the original string using the bytes
if let originalString = String(bytes: byteArray, encoding: .utf8) {
debugPrint(originalString) //->"test string"
} else {
print("*Bad encoding*")
}



By the way, your code can be shortened utilizing the functionality of Swift and Swift Standard Library.
Code Block
// Returns the byte array value after string value is appended to the resulting string array.
func binaryStringArray(array: [UInt8]) -> [String] {
return array.map { byte2Binary(byte: $0) }
}
// Converter - string byte to binary
func byte2Binary(byte: UInt8) -> String {
let result = String(byte, radix: 2)
let length = MemoryLayout<UInt8>.size * 8 //== 8
return String(repeating: "0", count: length - result.count) + result
}
let str: String = "test string"
let bytes: [UInt8] = Array(str.utf8)
// Iterate through the data string array and print the contents of that array
for value in binaryStringArray(array: bytes) {
print(value)
}


Can do this:

Code Block
var resultStr = ""
for value in binaryStringArray(array: bytes) {
let number = Int(strtoul(value, nil, 2))
if let unicode = UnicodeScalar(number) {
let c = Character(unicode)
resultStr.append(c)
}
}
print(resultStr)

Accepted Answer
You can make the Result output back to the bytes, then to the original string.

With your code, the Result output contains line break characters at each end of the binary string, so I used this String as Result outpuut.
Code Block
let resultOutput = """
01110100
01100101
01110011
01110100
00100000
01110011
01110100
01110010
01101001
01101110
01100111
"""


Using resultOutput, you can write something like this:
Code Block
//Convert the Result output back to the bytes
let byteArray = resultOutput.components(separatedBy: .whitespacesAndNewlines)
.compactMap {UInt8($0, radix: 2)}
//print(byteArray)
//->[116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 103]
//Construct the original string using the bytes
if let originalString = String(bytes: byteArray, encoding: .utf8) {
debugPrint(originalString) //->"test string"
} else {
print("*Bad encoding*")
}



By the way, your code can be shortened utilizing the functionality of Swift and Swift Standard Library.
Code Block
// Returns the byte array value after string value is appended to the resulting string array.
func binaryStringArray(array: [UInt8]) -> [String] {
return array.map { byte2Binary(byte: $0) }
}
// Converter - string byte to binary
func byte2Binary(byte: UInt8) -> String {
let result = String(byte, radix: 2)
let length = MemoryLayout<UInt8>.size * 8 //== 8
return String(repeating: "0", count: length - result.count) + result
}
let str: String = "test string"
let bytes: [UInt8] = Array(str.utf8)
// Iterate through the data string array and print the contents of that array
for value in binaryStringArray(array: bytes) {
print(value)
}


Thank you for the replies, both solutions worked the way they intend to work. OOPer's solution would be the best to implement in a separate module.
Converting Binary String back to original string using Swift
 
 
Q