3

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
  • 1
    Do you really want a string, or do you want an array back? Commented Sep 14, 2016 at 12:14

4 Answers 4

3
let binaryString = String(2, radix: 2)
let other = String(count: 8 - binaryString.characters.count, repeatedValue: Character("0")) + binaryString
Sign up to request clarification or add additional context in comments.

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
3

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

2 Comments

Can you please explain why of radix: 2 I mean 2?
@user2924482 Radix is the number base, in this case 2 means binary. en.wikipedia.org/wiki/Radix
0

Swift 5

var binaryString = String(2, radix: 2)
binaryString = String(repeating: "0", count: 8 - binaryString.count) + binaryString

Comments

0

The documentation for the FixedWidthInteger protocol brings an interesting example for representing the number’s binary:

extension FixedWidthInteger {
    var binaryString: String {
        var result: [String] = []
        for i in 0..<(Self.bitWidth / 8) {
            let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
            let byteString = String(byte, radix: 2)
            let padding = String(repeating: "0",
                                 count: 8 - byteString.count)
            result.append(padding + byteString)
        }
        return "0b" + result.reversed().joined(separator: "_")
    }
}


print(Int16.max.binaryString) // Prints "0b01111111_11111111"
print((101 as UInt8).binaryString) // Prints "0b11001001"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.