Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift. Get binary string from an integer

Tags:

swift

radix

I have binary 0000010 which is represented as an array of ints. From this binary I get an Integer:

let number = Int32([0, 0, 0, 0, 0, 1, 0].reduce(0, combine: {$0*2 + $1})) // number = 2

but when I want to inverse operation to get a String:

let binaryString = String(2, radix: 2) // binaryString = "10"

So seems radix cuts some bits if they are 0, how to return 5 more zeros?

like image 768
Matrosov Oleksandr Avatar asked Jun 23 '26 18:06

Matrosov Oleksandr


1 Answers

let binaryString = String(2, radix: 2)
let other = String(count: 8 - binaryString.characters.count, repeatedValue: Character("0")) + binaryString
like image 184
Mehdi Mirzaei Avatar answered Jun 26 '26 07:06

Mehdi Mirzaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!