bit shift - objective-c sscanf from NSData -
bit shift - objective-c sscanf from NSData -
i have btle device sending me bytes, of need compose 32 bit signed int, shift around, interpret. i'm using xcode 6.1.
the problem i'm having in converting bytes int32_t using sscanf works , doesn't. i'm not obj-c expert, not sure if right way @ all, using strtol wasn't working.
the entire function below:
- (double) parsemv2: (nsdata*) info { nsdata* sliceddata = [data subdatawithrange:nsmakerange(2, 4)]; const char *bytes = [sliceddata bytes]; int32_t value; double mv = 0; int sscanf_result = sscanf(bytes, "%4x", &value); if (1 == sscanf_result) { value <<= 3; // discard 3 important bits not part of value brings sign bit important bit position. value >>= 8; // discard 5 to the lowest degree important bits below noise levels. mv = ((double)value)*2048.0/16777216.0; // convert mv } else { nslog(@"💋💋💋 sscanf failed read bytes %4x (result = %d)", (int32_t) bytes, sscanf_result); } nslog(@"💋 mv2 = %f (bytes = %x", mv, (uint) bytes); nslog(@"----------------------------------"); homecoming mv; }
if set breakpoint after sscanf, value set right interpretation of bytes set zero. here output llvm:
(lldb) print bytes (const char *) $3 = 0x17ecceb8 "+\333\x91" (lldb) print value (int32_t) $4 = 0
here illustration sscanf 1 time again returns 0 value not 0 (don't since thought sscanf returns number of variables assigns to):
(lldb) print bytes (const char *) $6 = 0x176db558 ")z\x19x" (lldb) print value (int32_t) $7 = 383772
using sscanf
reading c-string don't have c-string. have sequence of bytes.
try way:
nsdata* sliceddata = [data subdatawithrange:nsmakerange(2, 4)]; const uint8_t *bytes = [sliceddata bytes]; int32_t value; memcpy(&value, bytes, 4);
and pointed out ken, easier way be:
int32_t value; [data getbytes:&value range:nsmakerange(2, 4)];
you may have worry byte ordering depending on how info created. may need add:
value = cfswapint32bigtohost(value); // or cfswapint32littletohost
objective-c bit-shift sscanf
Comments
Post a Comment