2

I am taking in a hexadecimal value and converting it into a binary number however, it is not printing out the leading zeros. I know that swift does not have a built in ability to do so like C. I am wondering if there is a way to print out any leading zeros when I know that the biggest the binary number will be is 16 characters. I have some code that runs for me by taking the hex number, converting it into a decimal number, and then into a binary number.

@IBAction func HextoBinary(_ sender: Any)
{
//Removes all white space and recognizes only text
let origHex = textView.text.trimmingCharacters(in: .whitespacesAndNewlines)
if let hexNumb_int = Int(origHex, radix:16)
 {
   let decNumb_str = String(hexNumb_int, radix:2)
   textView.text = decNumb_str
 }
}

Any assistance is greatly appreciated.

Slipp D. Thompson
  • 33,165
  • 3
  • 43
  • 43
Anavas
  • 55
  • 1
  • 8

1 Answers1

2

Another way to create a fixed length (having leading 0's) binary representation:

extension UnsignedInteger {
    func toFixedBinaryString(_ bits: Int = MemoryLayout<Self>.size*8) -> String {
        let uBits = UIntMax(bits)
        return (0..<uBits)
            .map { self.toUIntMax() & (1<<(uBits-1-$0)) != 0 ? "1" : "0" }
            .joined()
    }
}
extension SignedInteger {
    func toFixedBinaryString(_ bits: Int = MemoryLayout<Self>.size*8) -> String {
        return UIntMax(bitPattern: self.toIntMax()).toFixedBinaryString(bits)
    }
}

let b: UInt16 = 0b0001_1101_0000_0101
b.toFixedBinaryString(16) //=>"0001110100000101"
b.toFixedBinaryString()   //=>"0001110100000101"

let n: Int = 0x0123_CDEF
n.toFixedBinaryString(32) //=>"00000001001000111100110111101111"
n.toFixedBinaryString()   //=>"0000000000000000000000000000000000000001001000111100110111101111"
OOPer
  • 47,149
  • 6
  • 107
  • 142