Get Signed Integer from Swift String of Binary

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

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

Force binary number display Signed Integer?

0b11001010 is an integer literal and in print(0b11001010) its type is Int and the value is 202.

But you can create a signed 8-bit value with the same bit pattern:

let x = Int8(bitPattern: 0b11001010)
// Equivalent to:
// let x = Int8(bitPattern: 202)
print(x) // -54

using the Int8(bitPattern:) initializer:

Creates a new instance with the same memory representation as the given value.

(Here the compiler infers the type of the integer literal as UInt8.)

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 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)

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

Read integers from binary file in Swift

You can open a binary file using a function like this (Swift 5):

func getFile(forResource resource: String, withExtension fileExt: String?) -> [UInt8]? {
// See if the file exists.
guard let fileUrl: URL = Bundle.main.url(forResource: resource, withExtension: fileExt) else {
return nil
}

do {
// Get the raw data from the file.
let rawData: Data = try Data(contentsOf: fileUrl)

// Return the raw data as an array of bytes.
return [UInt8](rawData)
} catch {
// Couldn't read the file.
return nil
}
}

Usage:

if let bytes: [UInt8] = getFile(forResource: "foo", withExtension: "json") {
for byte in bytes {
// Process single byte...
}
}

Then simply iterate over the bytes and format them to your specifications.

In Swift I cant create a negative number in binary

Your value is not -5, but -123.

You can't get there with a direct assignment because the value is a signed Int and interpreted as 133.

To assign a negative value, use Int8(bitpattern:) to convert the value from a UInt8 to an Int8:

let signedInt = Int8(bitPattern: 0b10000101)
print(signedInt)
-123

-5 is 0b11111011 which is the 2's complement of 0b00000101.

To form the 2's complement, start with the binary pattern for 5:

0b00000101

invert all of the bits:

0b11111010

and add 1:

0b11111011

You can use UInt8(bitPattern:) to find the representation of the number:

let signedInt: Int8 = -5
print(String(UInt8(bitPattern: signedInt), radix: 2))
11111011


Related Topics



Leave a reply



Submit