Swift. Get binary string from an integer

若如初见. 提交于 2019-12-22 16:29:33

问题


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?


回答1:


let binaryString = String(2, radix: 2)
let other = String(count: 8 - binaryString.characters.count, repeatedValue: Character("0")) + binaryString



回答2:


The String constructor can't know how many zero bits the Integer had before the conversion. You'll have to handle that yourself.

By the way, Int also has the radix constructor, for converting strings into Int:

Int("0000010", radix: 2) // Returns 2


来源:https://stackoverflow.com/questions/39489422/swift-get-binary-string-from-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!