ios - 二进制字符串到人类可读字符串

标签 ios swift binary

我找到了一些关于这个主题的过时信息,但没有一个解决方案与当前的 Swift 版本匹配。所以我决定再问一遍!


我得到了这样一个字符串:

var string="abc"

...并使用以下代码将字符串转换为二进制代码:

let binaryString = (string.data(using: .utf8, allowLossyConversion: false)?.reduce("") { (a, b) -> String in a + String(b, radix: 2) })!

但是如何将特定的二进制字符串解码回人类可读的字符串呢??


Get from "110000111000101100011" -----> "abc"

最佳答案

在当前这种形式下,很难转换。但是,通过对获取二进制字符串的方式进行一些调整,这应该是可能的。

创建二进制字符串时,应始终填充 String(b, radix: 2) 返回的字符串,使其始终为 8 个字符。

现在,你可以

  1. 将二进制字符串分成 8 个字符的组。
  2. 将每个组转换成一个UInt8
  3. 将这些 UInt8 添加到一个数组中
  4. 使用数组创建一个Data
  5. 根据数据创建字符串

编辑:将字符串填充为 8 个字符的扩展:

extension String {
    func padTo8() -> String {
        if self.count < 8 {
            return String(Array(repeating: "0", count: 8-self.count)) + self
        } else {
            return self
        }
    }
}

完整代码如下:

extension Array {
    public func split(intoChunksOf chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            let endIndex = ($0.advanced(by: chunkSize) > self.count) ? self.count - $0 : chunkSize
            return Array(self[$0..<$0.advanced(by: endIndex)])
        }
    }
}

extension String {
    func padTo8() -> String {
        if self.count < 8 {
            return String(Array(repeating: "0", count: 8-self.count)) + self
        } else {
            return self
        }
    }

    // split(intoChunksOf:) implementation from SwiftyUtils
    // https://github.com/tbaranes/SwiftyUtils
    public func split(intoChunksOf chunkSize: Int) -> [String] {
        var output = [String]()
        let splittedString = self
            .map { $0 }
            .split(intoChunksOf: chunkSize)
        splittedString.forEach {
            output.append($0.map { String($0) }.joined(separator: ""))
        }
        return output
    }
}


let binaryString = ("abc".data(using: .utf8, allowLossyConversion: false)?.reduce("") { (a, b) -> String in a + String(b, radix: 2).padTo8() })!

let byteArray = binaryString.split(intoChunksOf: 8).map { UInt8(strtoul($0, nil, 2)) }
let string = String(bytes: byteArray, encoding: .utf8)

关于ios - 二进制字符串到人类可读字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139625/

相关文章:

ios - 如何从 GetCell 方法 UICollectionView 跳过单元格/不返回单元格

ios - 状态栏颜色 iOS

ios - 检测 "Done"按钮的点击事件(youtube视频)

ios - GameKit 中的 Swift 完成处理程序

c++ - 数组显示比正常情况更多的结果

ios - 为什么 UINavigationController 根 Controller 的 View 小于导航 Controller

ios - 如何在iOS应用程序中使用多任务处理?

ios - (UITabBarController *)self.window.rootViewController;

iphone - 苹果二进制文件有多安全( key 安全)

c - C语言中如何将二进制数组转换为十进制数