0

I am trying to convert Data to UnsafePointer. I found an answer here where I can use withUnsafeBytes to get the bytes.

Then I did a small test my self to see I could just print out the bytes value of the string "abc"

let testData: Data = "abc".data(using: String.Encoding.utf8)!

testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in

    NSLog("\(bytes.pointee)")

})

But the output is just the value of one character, which is "a".

2018-07-11 14:40:32.910268+0800 SwiftTest[44249:651107] 97

How could I get the byte value of all three characters then?

JLT
  • 3,052
  • 9
  • 39
  • 86

2 Answers2

1

The "pointer" points to the address of the first byte in the sequence. If you want to want a pointer to the other bytes, you have to use pointer arithmetic, that is, move the pointer to the next address:

testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
    NSLog("\(bytes.pointee)")
    NSLog("\(bytes.successor().pointee)")
    NSLog("\(bytes.advanced(by: 2).pointee)")
}

or

testData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
    NSLog("\(bytes[0])")
    NSLog("\(bytes[1])")
    NSLog("\(bytes[2])")
}

However, you must be aware of the byte size of testData and don't overflow it.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

You are getting '97' because 'bytes' is pointing to the staring address of the 'testdata'.

you can get byte value of all three OR n number of characters like in the following code :

let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
    {(bytes: UnsafePointer<UInt8>) -> Void in
        for idx in 0..<testData.count {
            NSLog("\(bytes[idx])")
        }
})
Rizwan
  • 3,324
  • 3
  • 17
  • 38