我找到了一些关于这个主题的过时信息,但没有一个解决方案与当前的 Swift 版本匹配。所以我决定再问一遍!
- http://swift.oz-apps.com/2015/09/convert-binary-string-to-integer/
- http://sketchytech.blogspot.de/2015/08/from-binary-to-decimal-values-in-swift.html
- https://www.dotnetperls.com/convert-string-byte-array-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 个字符。
现在,你可以
- 将二进制字符串分成 8 个字符的组。
- 将每个组转换成一个
UInt8
- 将这些
UInt8
添加到一个数组中 - 使用数组创建一个
Data
- 根据数据创建字符串
编辑:将字符串填充为 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/