I have found the issue. In order to make question focus on the issue, I edited and reformat the question.
History: Previously I was using NSData instead of Data. I should use Data so I changed the question. Using Data does not solve the problem. I reformat it a little bit to make the problem stands out. See answer if you have the same issue
===========
I am using Swift 3.1
I want to convert the sub-array of a byte array into Int.
This is what I do here.
// I am extracting every 4 from the dataBytes and convert it to int
var xDataArray = dataBytes[8...11]
let xData = Data(buffer: UnsafeBufferPointer(start: &xDataArray, count: xDataArray.count))
var xVal: Int32 = xData.withUnsafeBytes { $0.pointee }
xVal = Int32(bigEndian: xVal)
var yDataArray = dataBytes[12...15]
let yData = Data(buffer: UnsafeBufferPointer(start: &yDataArray, count: yDataArray.count))
var yVal: Int32 = yData.withUnsafeBytes { $0.pointee }
yVal = Int32(bigEndian: yVal)
The xVal and yVal are the same and they seem to be very large random number.


NSDatainstead ofData?NSDatainstead ofData, is because if I calldata.getBytes(&num, length: MemoryLayout<Int>.size)usingDatathen it will give a compiler error and force me to pass inUint8instead ofInt.Dataequivalent is very similar:Data(bytes: &src, count: MemoryLayout<Int>.size)int. When I useDatainstead ofNSDataI need to usecopyBytesbut it only acceptsutf8as input. Thanks for the help.copyBytes.Datahas appropriate API and is much more versatile thanNSData. Did you read the duplicate question round trip Swift number types to/from Data and its answers in your linked answer? It's very informative.