trying to convert NSData of type (BigEndian) from BlueTooth to Int of type Little Endian in Swift -


i trying convert 6 byte hex of type nsdata got via bluetooth connection appropriate integer values. know of type big endian , need covnert little endian. however, every time try convert it, can extract right data, results wrong, see playground code below:

var newdata = nsdata(bytes: [0x26, 0x01, 0x45, 0x01, 0x04, 0x5e, ] [uint8], length:6)   //var timedata  = newdata.subdatawithrange(nsmakerange(4,2)) //var heeldata = newdata.subdatawithrange(nsmakerange(2,2)) //var frontdata = newdata.subdatawithrange(nsmakerange(0,2))   var timedata:uint16 = 0  var heeldata:uint16 = 0 var frontdata:uint16 = 0   //var timedata = data.subdatawithrange(nsmakerange(4,2))  var timein: nsnumber = nsnumber(unsignedshort: 0) newdata.getbytes(&timein, range: nsrange(location: 4,length: 2)) timedata = cfswapint16bigtohost(timein.unsignedshortvalue) //24068   var heelin: nsnumber = nsnumber(unsignedshort: 0)  newdata.getbytes(&heelin, range: nsrange(location: 2, length: 2))  heeldata = cfswapint16bigtohost(heelin.unsignedshortvalue)  //325   var frontin: nsnumber = nsnumber(unsignedshort: 0)  newdata.getbytes(&frontin, range: nsrange(location: 0, length: 2))  frontdata = cfswapint16bigtohost(frontin.unsignedshortvalue)  //294 

nsnumber foundation class , in particular value type, , timein pointer number instance. extracting bytes pointer, not want , can cause kinds of undefined behavior or crashes.

what should extract bytes uint16 variable:

var timedata:uint16 = 0  newdata.getbytes(&timedata, range: nsrange(location: 4, length: 2)) timedata = cfswapint16bigtohost(timedata) // result: 1118 = 0x045e 

an alternative last conversion is

/// creates integer big-endian representation, changing /// byte order if necessary. timedata = uint16(bigendian: timedata)  

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -