Search code examples
swiftbinarybinaryfiles

String of Binary Values to Binary File


I have a large string (~600 bytes) of binary bits that I need to save into a binary file.

If I just save the string to a file using String.write then the 1's and 0's will be encoded as their Unicode/ASCII values.

I need it so that if I opened the file with xxd -b for example it would output the same binary bits as I currently have in the string.

How can I accomplish this?


Solution

  • If you have a string with a series of “0” and “1” characters, and want a binary representation, you can do:

    extension String {
        var binaryData: Data {
            let values = try! NSRegularExpression(pattern: "[01]{8}")
                .matches(in: self, range: NSRange(startIndex..., in: self))
                .compactMap { Range($0.range, in: self) }
                .compactMap { self[$0] }
                .compactMap { UInt8($0, radix: 2) }
            return Data(values)
        }
    }
    

    Thus

    let input = "010000010100001001000011"
    let data = input.binaryData               // 0x41 0x42 0x43
    

    You can then write that Data to a file, or do whatever you want with it.