Mahendran Candy
Mahendran Candy

Reputation: 1144

What is the equivalent data type for byte in iOS swift?

In Java we have data type called byte but in Swift there is no byte data type available.

In the example below I typecasted the ASCII (0xAF = 175) value by using byte data type.

byte abyte = (byte) 0xAF;

And the result is abyte= -89

How do I acheive this in Swift?

Upvotes: 3

Views: 11152

Answers (3)

Lahiru Pinto
Lahiru Pinto

Reputation: 1681

In kotlin use byteArray.toUByteArray() to convert to UInt8

Upvotes: 0

Ian
Ian

Reputation: 285

Swift bytes is [UInt8], UInt8 is 0 ... 255, Int8 is -128 ~ 127, you can get the Int8 value which like java byte with follow code.

extension UInt8 {
    var int8: Int8 {
        return Int8(self > 127 ? Int(self) - 256 : Int(self))
    }
}

Upvotes: 5

Daniel K
Daniel K

Reputation: 1129

The data type is Unsigned Int 8 (UInt8).

var byte:UInt8 = 0xAF

For a string of bytes:

var bytes:[UInt8] = [0xAF,0xAB]

For the bytes from data:

var data = Data()
var bytes = data.bytes //[UInt8]

Upvotes: 13

Related Questions