Mickael Belhassen
Mickael Belhassen

Reputation: 3342

Swift: Byte array to decimal value

In my project, I communicate with a bluetooth device, the bluetooth device must send me a timestamp second, I received in byte:

[2,6,239]

When I convert converted to a string:

let payloadString = payload.map {
            String(format: "%02x", $0)
        }

Output:

["02", "06","ef"]

When I converted from the website 0206ef = 132847 seconds

How can I directly convert my aray [2,6,239] in second (= 132847 seconds)? And if it's complicated then translate my array ["02", "06,"ef"] in second (= 132847 seconds)

Upvotes: 2

Views: 1292

Answers (2)

Martin R
Martin R

Reputation: 539685

The payload contains the bytes of the binary representation of the value. You convert it back to the value by shifting each byte into its corresponding position:

let payload: [UInt8] = [2, 6, 239]
let value = Int(payload[0]) << 16 + Int(payload[1]) << 8 + Int(payload[2])
print(value) // 132847

The important point is to convert the bytes to integers before shifting, otherwise an overflow error would occur. Alternatively, with multiplication:

let value = (Int(payload[0]) * 256 + Int(payload[1])) * 256 + Int(payload[2])

or

let value = payload.reduce(0) { $0 * 256 + Int($1) }

The last approach works with an arbitrary number of bytes – as long as the result fits into an Int. For 4...8 bytes you better choose UInt64 to avoid overflow errors:

let value = payload.reduce(0) { $0 * 256 + UInt64($1) }

Upvotes: 2

Rizwan
Rizwan

Reputation: 3666

payloadString string can be reduced to hexStr and then converted to decimal

var payload = [2,6,239];
let payloadString = payload.map {
    String(format: "%02x", $0)
}

//let hexStr = payloadString.reduce(""){$0 + $1}
let hexStr = payloadString.joined()
if let value = UInt64(hexStr, radix: 16) {
    print(value)//132847
}

Upvotes: 1

Related Questions