0

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?

Andrew
  • 1,947
  • 2
  • 23
  • 61

1 Answers1

1

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)

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194