Reputation: 2157
I have such int number:
266
I would like to convert it to binary string. In android I use such method:
Integer.toBinaryString(266)
and the output was:
000100001010
I ios I tried to use string with radix:
String(266, radix: 2)
but I got:
100001010
I found such question-answer and used such code:
func pad(string : String, toSize: Int) -> String {
var padded = string
for _ in 0..<(toSize - string.count) {
padded = "0" + padded
}
return padded
}
and:
pad(string: String(ResumeController.userData.edu!), toSize: 12)
and got:
000100001010
can you please explain why external function which added some 0s works similar to the kotlin one which is built-in? And also one more question - how I can get this number back from this binary string?
Upvotes: 0
Views: 743
Reputation: 27221
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)
Upvotes: 1