Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to convert text to binary code in Swift

1 Answer

0 votes
import Foundation

func text2bin(_ txt: String) -> String {
    var bin = ""
    
    for char in txt {
        let asciiValue = Int(char.asciiValue ?? 0)
        let binaryString = String(asciiValue, radix: 2)
        let paddedBinaryString = binaryString.count < 8 ? String(repeating: "0", count: 8 - binaryString.count) + binaryString : binaryString
        bin += paddedBinaryString + " "
    }
    
    return bin
}

print(text2bin("Swift Programming"))




/*
run:

01010011 01110111 01101001 01100110 01110100 00100000 01010000 01110010 01101111 01100111 01110010 01100001 01101101 01101101 01101001 01101110 01100111 

*/

 



answered Nov 18, 2024 by avibootz

Related questions

1 answer 76 views
2 answers 135 views
2 answers 171 views
...