Swift 2進数出力のゼロサプレス 改:指定桁数で区切り表示
出力:00110
見やすくするために4桁で区切りたい。
ゴール:0 0110
対応
extension String {
func zerosuppression(digit: Int, split: Int = 0) -> String {
var result = String(repeating: "0", count: digit - self.count) + self
if split > 0 {
var splitIndex = split
while result.count > splitIndex {
result.insert(" ", at: result.index(result.endIndex, offsetBy: -(splitIndex)))
splitIndex = splitIndex + split + 1
}
}
return result
}
}
print("\(String(6, radix: 2)).zerosuppression(digit: 8, split: 4)")
出力:0000 0110
print("\(String(6, radix: 2)).zerosuppression(digit: 8, split: 2)")
出力:00 00 01 10


