How to convert a decimal number to binary in Swift?
You can convert the decimal value to a human-readable binary representation using the String
initializer that takes a radix
parameter:
let num = 22
let str = String(num, radix: 2)
print(str) // prints "10110"
If you wanted to, you could also pad it with any number of zeroes pretty easily as well:
Swift 5
func pad(string : String, toSize: Int) -> String {
var padded = string
for _ in 0..<(toSize - string.count) {
padded = "0" + padded
}
return padded
}
let num = 22
let str = String(num, radix: 2)
print(str) // 10110
pad(string: str, toSize: 8) // 00010110
Convert between Decimal, Binary and Hexadecimal in Swift
Both String
and Int
have initializers which take a radix
(base). Combining those, you can achieve all of the conversions:
// Decimal to binary
let d1 = 21
let b1 = String(d1, radix: 2)
print(b1) // "10101"
// Binary to decimal
let b2 = "10110"
let d2 = Int(b2, radix: 2)!
print(d2) // 22
// Decimal to hexadecimal
let d3 = 61
let h1 = String(d3, radix: 16)
print(h1) // "3d"
// Hexadecimal to decimal
let h2 = "a3"
let d4 = Int(h2, radix: 16)!
print(d4) // 163
// Binary to hexadecimal
let b3 = "10101011"
let h3 = String(Int(b3, radix: 2)!, radix: 16)
print(h3) // "ab"
// Hexadecimal to binary
let h4 = "face"
let b4 = String(Int(h4, radix: 16)!, radix: 2)
print(b4) // "1111101011001110"
How to convert a binary to decimal in Swift?
Update for Swift 2: All integer types have an
public init?(_ text: String, radix: Int = default)
method now, which converts a string to an integer according to
a given base:
let binary = "11001"
if let number = Int(binary, radix: 2) {
print(number) // Output: 25
}
(Previous answer:) You can simply use the BSD library function strtoul()
, which converts a string to
a number according to a given base:
let binary = "11001"
let number = strtoul(binary, nil, 2)
println(number) // Output: 25
How to calculate Decimal number of one's compliment in swift?
You can do this without even converting to binary:
let n = 633
let result = 255 - n % 256
print(result) // 134
Modding the number with 256
yields the lower order 8 bits and subtracting that from 255
performs the 1's complement.
You can get the same result by using & 255
or & 0xff
to get the low order 8 bits:
let result = 255 - n & 255
You can also perform the 1's complement by XOR-ing with 255
using the ^
operator:
let result = (n & 255) ^ 255
If you insist on converting to binary and doing the complement, then you could do it like this:
let n = 633
let binary = String(n, radix: 2)
let lowbits = ("0000000" + binary).suffix(8)
let complement = String(lowbits.map { $0 == "0" ? "1" : "0" })
let result = Int(complement, radix: 2)!
print(result) // 134
How I can convert int to binary string swift?
There is a function that can convert to integer Int("000100001010", radix: 2)
To append zeroes, use this:let str = String(repeating: "0", count: amount)
Convert a String to binary in swift?
Use func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Example:
Swift 5
let string = "The string"
let binaryData = Data(string.utf8)
Swift 3
let string = "The string"
let binaryData: Data? = string.data(using: .utf8, allowLossyConversion: false)
EDIT: Or wait, do you need binary representation of you data or string of 0/1?
EDIT:
For string of 0/1 use something like:
let stringOf01 = binaryData?.reduce("") { (acc, byte) -> String in
acc + String(byte, radix: 2)
}
EDIT: Swift 2
let binaryData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Related Topics
Wrong Specialized Generic Function Gets Called in Swift 3 from an Indirect Call
How to Return an Object That I Create in My Data Service Class Through Firebase
Having Hard Time Implement a Simple Singleton in Swift
Changing Text Color of Datepicker
How to Make My Exponentiation Operator Work With All Numeric Types in Swift
How to Easily Duplicate/Copy an Existing Realm Object
How to Import a Swift File from Another Swift File
Swiftui 2: the Way to Open View in New Window
How to Multiply Two Arrays Element-Wise
JavaScript Synchronous Native Communication to Wkwebview
Xcode 8/Swift 3: Simple Uipicker Code Not Working
How to Determine If a String Contains a Character from a Set in Swift
Swiftui Picker Separate Texts For Selected Item and Selection View
How to Lock Orientation of One View Controller to Portrait Mode Only in Swift