[英]How I can convert int to binary string swift?
我有這樣的整數:
266
我想將其轉換為二進制字符串。 在 android 我使用這樣的方法:
Integer.toBinaryString(266)
output 是:
000100001010
我 ios 我嘗試使用帶基數的字符串:
String(266, radix: 2)
但我得到了:
100001010
我找到了這樣的問題答案並使用了這樣的代碼:
func pad(string : String, toSize: Int) -> String {
var padded = string
for _ in 0..<(toSize - string.count) {
padded = "0" + padded
}
return padded
}
和:
pad(string: String(ResumeController.userData.edu!), toSize: 12)
並得到:
000100001010
您能否解釋一下為什么添加了一些 0 的外部 function 與內置的 kotlin 類似? 還有一個問題——如何從這個二進制字符串中取回這個數字?
There is a function that can convert to integer Int("000100001010", radix: 2)
To append zeroes, use this: let str = String(repeating: "0", count: amount)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.