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?
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.