Swift中字符串转二进制丢失一位的问题及修复咨询
Let's break down what's going wrong here, then fix it:
The Root Cause
Your current code adds a single leading 0 to each UTF-8 character's binary string, which works for characters whose binary representation is exactly 7 digits long (like a, b, c, d—their ASCII values are 97-100, binary is 7 digits). But for characters with shorter binary strings (like spaces, which are ASCII 32, binary 100000—only 6 digits), adding one 0 only makes it 7 digits instead of the required 8 bits for a full UTF-8 byte. This missing bit shifts all subsequent binary data, leading to incorrect characters when you convert back.
The Fix
Instead of hardcoding a single leading 0, we need to pad each binary string to exactly 8 digits with leading zeros to ensure every UTF-8 byte is represented correctly. Swift's String has a handy padding(toLength:withPad:startingAt:) method for this:
extension String { func toBinary() -> String { return self.utf8.reduce("", { result, byte in // Convert the UInt8 byte to its binary string representation let binaryString = String(byte, radix: 2) // Pad the binary string to 8 digits with leading zeros let paddedBinary = binaryString.padding(toLength: 8, withPad: "0", startingAt: 0) // Append the padded string to the result return result + paddedBinary }) } }
Testing the Fix
For "abc d", this will generate the correct 8-bit segments for each character:
a→01100001b→01100010c→01100011- Space →
00100000 d→01100100
When concatenated, this gives the correct binary string: 0110000101100010011000110010000001100100, which converts back to the original "abc d" instead of "abc@".
内容的提问来源于stack exchange,提问作者mikro098

