How to convert int to binary with leading zeros in Swift

1 Answer

0 votes
import Foundation

/// Converts an integer to a binary string with leading zeros.
/// - Parameters:
///   - num: The integer value to convert.
///   - bits: The target bit width determining the number of leading zeros.
/// - Returns: A zero-padded binary string.
func intToBinary(_ num: Int, bits: Int) -> String {
    // 1. Convert the integer to a binary string using radix 2
    let binaryString = String(num, radix: 2)
    
    // 2. Pad with leading zeros if the string is shorter than the requested bit width
    if binaryString.count < bits {
        let padding = String(repeating: "0", count: bits - binaryString.count)
        return padding + binaryString
    }
    
    return binaryString
}

// MARK: - Program Execution

// Define the data provided
let num = 153

// 1. Convert to an 8-bit binary representation (153 = 10011001 in binary)
let binStr8 = intToBinary(num, bits: 8)

// 2. Convert to a 16-bit binary representation (0000000010011001)
let binStr16 = intToBinary(num, bits: 16)

// Display the results
print("Original Integer: \(num)")
print("Binary (8-bit)  : \(binStr8)")
print("Binary (16-bit) : \(binStr16)")


/*
run:

Original Integer: 153
Binary (8-bit)  : 10011001
Binary (16-bit) : 0000000010011001

*/

 



answered 1 day ago by avibootz
...