import Foundation
/// Converts a character to its 8-bit binary representation.
///
/// - Parameter character: The character to convert.
/// - Returns: An 8-bit binary string.
/// - Throws: An error if the character cannot be represented as a single byte.
func charToBits(_ character: Character) throws -> String {
guard let asciiValue = character.asciiValue else {
throw NSError(
domain: "CharacterError",
code: 1,
userInfo: [
NSLocalizedDescriptionKey:
"Character is not a single-byte ASCII character."
]
)
}
return String(asciiValue, radix: 2).leftPad(toLength: 8, withPad: "0")
}
/// Prints a character and its binary representation.
///
/// - Parameter character: The character to display.
func printCharacterBits(_ character: Character) {
do {
let bits = try charToBits(character)
print("Character: '\(character)'")
print("Decimal : \(character.asciiValue!)")
print("Binary : \(bits)")
} catch {
print("Error: \(error.localizedDescription)")
}
}
/// Helper extension for left-padding strings.
extension String {
func leftPad(toLength length: Int, withPad pad: Character) -> String {
if count >= length {
return self
}
return String(repeating: String(pad), count: length - count) + self
}
}
// ------------------------------------------------------------------
// Usage examples
// ------------------------------------------------------------------
printCharacterBits("A")
print()
printCharacterBits("a")
print()
printCharacterBits("5")
print()
printCharacterBits("@")
/*
run:
Character: 'A'
Decimal : 65
Binary : 01000001
Character: 'a'
Decimal : 97
Binary : 01100001
Character: '5'
Decimal : 53
Binary : 00110101
Character: '@'
Decimal : 64
Binary : 01000000
*/