Doug
Doug

Reputation: 597

Objective C: converting hex (NSInline) to decimal per byte

I'm converting a hex characteristic.value (NSinline) to decimal.

This piece of data is the following: <d1448fe0 a1b1c827 efecdf87 a05b1907 5e4e62ec> which is 20 bytes. I want to then store each byte in an array of size 20. I'm curious if there is a more efficient way to parse this one byte at a time. My current code pasted below is working, but it's slow given my sampling rate is about 250 Hz.

I put the hex value into a string then into an array of chars then parse loop through the whole thing.

Any ideas? Thanks in advance

            int xval[20];
            NSString *val = @"";
            val = [val stringByAppendingFormat: @"%@",characteristic.value];

            const char *c = [val UTF8String];
            int number = [temp intValue];
            int counter_filler = 0;
            NSString *toFill = @"";
            int xval_counter = 0;
            unsigned binar;


            for (int i = 0; i < strlen(c);i++)
            {
                if (c[i] != '<' && c[i] != '>' && c[i] != ' ')
                {
                if (counter_filler == 2)
                {
                    counter_filler = 0;
                    toFill = @"";     
                }
                // make it a string
                toFill = [toFill stringByAppendingFormat: @"%c",c[i]];
                if (counter_filler == 1)
                {
                     NSScanner *scanner = [NSScanner scannerWithString:toFill];
                    [scanner scanHexInt:&binar];
                    xval[xval_counter] = binar;
                    xval_counter++;
                }

                counter_filler++;
                }

            }

Upvotes: 0

Views: 518

Answers (1)

rmaddy
rmaddy

Reputation: 318774

If characteristic.value is actually an NSData object, you can replace all of your code with this:

uint8_t xval[20];
[characteristic.value getBytes:xval length:sizeof(xval)];

That's it. That will put 20 bytes from characteristic.value into the xval byte array.

uint8_t is an unsigned integer type that holds one 8-bit byte.

BTW - never rely on the output of an object's description method. When you use stringWithFormat: and the %@ format specifier for an object, this results in the object's description method being called to get the string representation. The output of the description method is not documented and can change over time. Always use appropriate methods of the class to get its values.

Upvotes: 1

Related Questions