1

I have a data like a bellow:

let data = Data(bytes: [206, 66, 49, 62])

Then I used this extension (from How to convert Data to hex string in swift) to convert to a hex string:

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let hexDigits = Array((options.contains(.upperCase) ? "0123456789ABCDEF" : "0123456789abcdef").utf16)
        var chars: [unichar] = []
        chars.reserveCapacity(2 * count)
        for byte in self {
            chars.append(hexDigits[Int(byte / 16)])
            chars.append(hexDigits[Int(byte % 16)])
        }

        return String(utf16CodeUnits: chars, count: chars.count)
    }
}

And then it is giving "ce42313e" as hex string. Now I am trying to convert this to Signed integer (32-bit) Two's complement .. I tried a couple of ways but not find anything perfectly.

When I give "ce42313e" in this bellow link under hex decimal the value is -834522818

http://www.binaryconvert.com/convert_signed_int.html

bellow is one of those I tried to convert "ce42313e" to int and it's giving me 3460444478 ..instead of -834522818 .

let str = value
let number = Int(str, radix: 16)

Please help out to get that value.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
tp2376
  • 690
  • 1
  • 7
  • 23

1 Answers1

0

Int(str, radix: 16) interprets the string as the hexadecimal representation of an unsigned number. You could convert it to Int32 with

let data = Data(bytes: [206, 66, 49, 62])
let str = data.hexEncodedString()
print(str) // ce42313e

let number = Int32(truncatingBitPattern: Int(str, radix: 16)!)
print(number) // -834522818

But actually you don't need the hex representation for that purpose. Your data is the big-endian representation of a signed 32-bit integer, and this is how you can get the number from the data directly:

let data = Data(bytes: [206, 66, 49, 62])
let number = Int32(bigEndian: data.withUnsafeBytes { $0.pointee })
print(number) // -834522818
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382