Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

How I can convert int to binary string swift?

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?

question from:https://stackoverflow.com/questions/65859774/how-i-can-convert-int-to-binary-string-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...