let dataBytes = characteristic.value
let dataLength = dataBytes.length
var dataArray = [Double](count: 4, repeatedValue: 0.0)
dataBytes.getBytes(&dataArray, length: dataLength)
func filter(acceleration : Double) -> Double{
dir = (acceleration * HIGHPASS_FILTER) + (dir * (1.0 - HIGHPASS_FILTER))
return Double(acceleration - dir)
}
xPos = filter(dataArray[1])
yPos = filter(dataArray[2])
zPos = filter(dataArray[3])
Here's my Swift code. My problem is that dataBytes prints out this:
<5fb9f940 f940fe00 fe002000 2000>
<60b9f940 f940fe00 fe402000 2000>
<61b9f980 f980fe00 fe002000 2000>
<67b9f940 f980fe00 fe002000 2000>
<68b9f980 f980fe00 fe002000 2000>
But dataArray prints out:
[6.89325535931183e-304, 6.79049015671387e-313, 0.0, 0.0]
[123919.578362877, 6.79049015671387e-313, 0.0, 0.0]
[6.89325535931183e-304, 6.79049015671387e-313, 0.0, 0.0]
[6.89325535931183e-304, 6.79049015671387e-313, 0.0, 0.0]
[6.89325535931183e-304, 6.79049015671387e-313, 0.0, 0.0]
[6.89325622848131e-304, 6.79049015671387e-313, 0.0, 0.0]
I do not understand why the array is not copying the values from NSData, also, yPos and zPos are getting numbers when I display them even though they should be 0.0 according to dataArray.
I am literally about to start flipping tables because I have went through every question about converting NSData to NSString, String, Integer, Decimal, Hex, Hex String, NSArray... Nothing has helped me with this problem.
Also, when every I try to do something like
xPos = round(filter(dataArray[1]))
I get 0.0. Can anybody help me with this problem? I would extraordinarily grateful!
Please don't direct me to another answer, I can 99.999% guarantee that I have seen or tried it already, even the ones written in objective-C.
You should know the data type of the dataBytes array , then you have to convert accordingly. You can change the below data type(UInt32) and experiment in playground.
Note - I have tried the below code with Xcode 7 beta 4 playground.
var arr : [UInt32] = [32,4,123,4,5,2];
let dataBytes = NSData(bytes: arr, length: arr.count * sizeof(UInt32))
// let dataBytes = characteristic.value
let dataLength = dataBytes.length
var dataArray = [UInt32](count: 4, repeatedValue: 0)
dataBytes.getBytes(&dataArray, length: dataLength)
let xPos = UInt32(dataArray[0])
let yPos = UInt32(dataArray[1])
let zPos = UInt32(dataArray[2])
print("\(xPos) \(yPos) \(zPos)");
For Multiple Data type Array
import Foundation
var arr = [32,4,4,5,2,"KP"];
let dataBytes = NSData(bytes: arr, length: arr.count * sizeof(AnyObject))
// let dataBytes = characteristic.value
let dataLength = dataBytes.length
var dataArray = [AnyObject](count: 6, repeatedValue: 0)
dataBytes.getBytes(&dataArray, length: dataLength)
let xPos: (AnyObject) = dataArray[0]
let yPos: (AnyObject) = dataArray[1]
let zPos: (AnyObject) = dataArray[5]
print("\(xPos) \(yPos) \(zPos)");
You can identify the datatype by using the below code
if let string = x as? String //Int,Float...
{
print("I'm a string: \(string)")
}