0

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?

1
  • Why do you use a string (of "0" and "1" characters) for the bits, and not a more appropriate data structure, like Data? Commented Jun 21, 2020 at 15:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.