Get signed integer from swift string of binary
Playing around you can get the desired result as follows:
let binaryString = "1111111110011100"
print(Int(binaryString, radix: 2)!)
print(UInt16(binaryString, radix: 2)!)
print(Int16(bitPattern: UInt16(binaryString, radix: 2)!))
Output:
65436
65436
-100
The desired result comes from creating a signed Int16
using the bit pattern of a UInt16
.
Swift. Get binary string from an integer
let binaryString = String(2, radix: 2)
let other = String(count: 8 - binaryString.characters.count, repeatedValue: Character("0")) + binaryString
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)
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
Swift - Convert a binary string to its ascii values
You may need to split the input binary digits into 8-bit chunks, and then convert each chunk to an ASCII character. I cannot think of a super simple way:
var binaryBits = "010010000110010101111001"
var index = binaryBits.startIndex
var result: String = ""
for _ in 0..<binaryBits.characters.count/8 {
let nextIndex = binaryBits.index(index, offsetBy: 8)
let charBits = binaryBits[index..<nextIndex]
result += String(UnicodeScalar(UInt8(charBits, radix: 2)!))
index = nextIndex
}
print(result) //->Hey
Convert a binary string into an array of integers in swift 3
A possible solution (now updated for Swift 4 and later):
let zeroOneString = "01101010101001010111"
let resultArray = zeroOneString.compactMap { char in
char == "0" ? 0 : char == "1" ? 1 : nil
}
print(resultArray) // [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1]
zeroOneString.compactMap
maps the sequences of all characters in the string.
The closure maps "0" to 0
and "1" to 1
. Everything else is mapped to nil
and ignored by compactMap
.
String of Binary Values to Binary File
If you have a string with a series of “0” and “1” characters, and want a binary representation, you can do:
extension String {
var binaryData: Data {
let values = try! NSRegularExpression(pattern: "[01]{8}")
.matches(in: self, range: NSRange(startIndex..., in: self))
.compactMap { Range($0.range, in: self) }
.compactMap { self[$0] }
.compactMap { UInt8($0, radix: 2) }
return Data(values)
}
}
Thus
let input = "010000010100001001000011"
let data = input.binaryData // 0x41 0x42 0x43
You can then write that Data
to a file, or do whatever you want with it.
Related Topics
Nstableview Inside Nspopover Looks Different as Standalone
Dynamic Uicollectionview Inside Dynamic Uitableviewcell
From the Swift Repl, How to Get a List of Available Modules
Is Dispatchsemaphore a Good Replacement for Nslock
How to Process an Array of Task Asynchronously with Swift Combine
How to Migrate Core Data's Data to App Group's Data
Properly Using Firebase Cloud Functions and Stripe
How to Call a Generic Swift Function When None of the Arguments Provides the Generic Type
Xcode Error - Undefined Symbols for Architecture X86_64
Correct Way to Call "Realloc" in Swift with a Float Array
How to Detect If a Observable Has Not Emitted Any Events for Specific Time in Rxswift
How to Understand What Is Causing a Crash Involving '_Nstouchbarfinderobservation'
Nsdateformatter Detect 24-Hour Clock in Os X and iOS
How to Create an Uppercase Version of a String in Swiftui
Deleting with One-To-Many Relationship
How to Save a Generic Measurement<Unit> in Core Data
Swift Threading with Dispatchgroup
Syncconfiguration Deprecated, What Is the Proper Use of Syncuser.Configuration()