How to print the bits of a character in Swift

4 Answers

0 votes
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

*/

 



answered Oct 16 by avibootz
0 votes
import Foundation

// Swift Character values represent Unicode extended grapheme clusters, 
// not just ASCII characters. 

// Display the Unicode scalar value in binary
func unicodeCharacterBits(_ character: Character) -> String? {
    guard let scalar = character.unicodeScalars.first else {
        return nil
    }

    return String(scalar.value, radix: 2)
}

// Usage
if let bits = unicodeCharacterBits("é") {
    print(bits)
}


/*
run:

11101001

*/

 



answered Oct 16 by avibootz
0 votes
import Foundation

// Unicode - fixed-width 32-bit representation
func unicodeCharacterBits32(_ character: Character) -> String? {
    guard let scalar = character.unicodeScalars.first else {
        return nil
    }

    let binary = String(scalar.value, radix: 2)
  
    return String(repeating: "0", count: 32 - binary.count) + binary
}

// Usage
if let bits = unicodeCharacterBits32("é") {
    print(bits)
}


/*
run:

00000000000000000000000011101001

*/

 



answered Oct 16 by avibootz
0 votes
import Foundation

// For ASCII characters, Swift's built-in formatting capabilities allow 
// a concise implementation
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
    }
}

func charToBits(_ character: Character) -> String? {
    guard let value = character.asciiValue else {
        return nil
    }

    return String(value, radix: 2).leftPad(toLength: 8, withPad: "0")
}

// Usage
if let bits = charToBits("a") {
    print(bits)
}


/*
run:

01100001

*/

 



answered Oct 16 by avibootz
...