0

I was trying to implement the function which takes String and returns string which consists of bits. I'm iterating through the utf8 representation of String and using reduce to append next letters. The problem is that Swift didn't add leading bits so I had to add them manually. When converting strings like "abcd", "fgh" etc it works fine but for example "abc d" produces string which is missing one bit.

My implementation:

extension String {
    func toBinary() -> String {

        return self.utf8.reduce("", { (result, ui) -> String in
            result + "0" + String(utf, radix: 2)
        })
    }
}

and "abc d".toBinary() returns:

011000010110001001100011010000001100100 when the proper representation is:

0110000101100010011000110010000001100100

When I'm converting binary back to String it works fine for strings without space but in this case it returns different string, for example: "abc@"

Is there any way to fix this?

1
  • String(utf, radix: 2) returns a binary without any leading zeros. Your code assume this string will always be 7 characters but that's an invalid assumption. Commented May 15, 2018 at 21:40

1 Answer 1

4

As @rmaddy noted in the comments, your code assumes String(utf, radix: 2) is returning a 7 character result. In reality, it could return a string from 1 to 8 characters.

One way to fix that would be to turn that string into an Int and then format that Int with leading zeros:

extension String {
    func toBinary() -> String {

        return self.utf8.reduce("", { (result, utf) -> String in
            result + String(format: "%08d", Int(String(utf, radix: 2))!)
        })
    }
}

Test:

print(" ".toBinary())
00100000

Other conversions of UInt8 to an 8-character binary String:

  1. String(("0000000" + String(utf, radix: 2)).suffix(8))
  2. String(String(256 + Int(utf), radix: 2).dropFirst())
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.