[英]Swift - converting data to decimal values
I'm getting data via BLE and I want to convert them into decimal values, however I suspect I do something wrong because value range appears to be incorrect 我正在通过BLE获取数据,并且想将它们转换为十进制值,但是我怀疑我做错了,因为值范围似乎不正确
from BLE I receive characteristic.value
从BLE我收到characteristic.value
24ffa400 6d08fcff fffffbff 0d001500 5eff
which is constructed maily of IMU values. 它是由IMU值构成的。
when I try to convert the first two bytes, in this example 24ff
which is accelerometer X axis value, I get a value from range 1000-30000 (I introduced some dynamic movement to the sensor to see how the value is changing). 当我尝试转换前两个字节(在此示例中为24ff
,它是加速度计X轴值)时,得到的值在1000-30000范围内(我向传感器引入了一些动态运动以查看该值如何变化)。
This must be wrong since docs say that accelerometer scale is ±16G
There are two more important information: 这一定是错误的,因为文档说加速度计的刻度为±16G
还有两个更重要的信息:
sequence of bytes in frame goes as follows: [LSB, MSB] 帧中的字节序列如下:[LSB,MSB]
values are 16bit and utilizes two's complement 值是16位,并利用二进制补码
this is how I convert data into decimal value: 这就是我将数据转换为十进制值的方式:
class func getAccelerometerData(value: NSData) -> [String] {
let dataFromSensor = dataToSignedBytes8(value)
let bytes:[Int8] = [dataFromSensor[1], dataFromSensor[0]]
let u16 = UnsafePointer<Int16>(bytes).memory
return([twosComplement(u16)])
}
class func twosComplement(num:Int16) -> String {
var numm:UInt16 = 0
if num < 0 {
let a = Int(UInt16.max) + Int(num) + 1
numm = UInt16(a)
}
else { return String(num, radix:10) }
return String(numm, radix:10)
}
I suppose I should obtain values from range <-16:16> instead of huge values I mentioned above, what is wrong with my approach? 我想我应该从范围<-16:16>中获取值,而不是上面提到的巨大值,我的方法有什么问题?
Thanks in advance 提前致谢
EDIT: Missing method implementation 编辑:缺少方法实现
class func dataToSignedBytes8(value : NSData) -> [Int8] {
let count = value.length
var array = [Int8](count: count, repeatedValue: 0)
value.getBytes(&array, length:count * sizeof(Int8))
return array
}
Given some NSData
, 给定一些NSData
,
let value = NSData(bytes: [0x24, 0xff, 0xa4, 0x00] as [UInt8], length: 4)
print(value) // <24ffa400>
you can retrieve the first two bytes in [LSB, MSB] order as a signed 16-bit integer with 您可以按[LSB,MSB]顺序将前两个字节作为带符号的16位整数检索,
let i16 = Int16(littleEndian: UnsafePointer<Int16>(data.bytes).memory)
print(i16) // -220
This number is in the range -32768 .. 32767
and must be scaled to the floating point range as per the specification of the device, for example: 此数字的范围是-32768 .. 32767
并且必须根据设备的规格将其缩放到浮点范围,例如:
let scaled = 16.0 * Double(i16)/32768.0
print(scaled) // -0.107421875
scaled
is a Double
and can be converted to a string with String(scaled)
, or using a NSNumberFormatter
. scaled
是Double
,可以使用String(scaled)
或使用NSNumberFormatter
转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.