Home > Software design >  How do I convert Data to signed Int?
How do I convert Data to signed Int?

Time:11-15

I'm in an iOS project where we convert incoming Data to a byteArray. It looks something like this:

class ViewController: UIViewController {
    let data: Data? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()

        guard let data = data else { return }

        [UInt8](data).forEach { print("--Doing stuff here", $0) }
    }
}

Now, there's a similar project in Android studio using Kotlin that also converts Data to a byteArray. BUT it turns out that ByteArray in Kotlin is signed not unsigned (I'm guessing Int8).

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte/

Represents a 8-bit signed integer.

To me this doesn't make any sense. In my world a byteArray is an array of uInt8. But perhaps I don't know this stuff well enough... care to explain anyone?

Anyway, the issue is that we need to take negative numbers. Obviously this works with Kotlin´s signed Int but not with iOS since uInt8 can't store negative numbers.

So, how do I convert Data to Int8? I tried like this:

[Int8](data).forEach { print("--Doing stuff here", $0) }

But I get an error saying No exact matches in call to initializer

So how do I do it?

CodePudding user response:

Here is one way of doing the conversion tested on Online Swift Playground:

let data = Data([1, 50, 215, 255]) 
var bytes: [Int8] = data.map { Int8(bitPattern: $0) }
print(bytes) // [1, 50, -41, -1]
  • Related