0

I'm doing a project and I have to use Bluetooth and apparently, all the incoming data need to be in NSData format.

I'm using the implementation from the question Best way to serialize a NSData into an hexadeximal string but the conversion is incorrect.

The main code snippet is this:

for (int i = 0; i < dataLength; ++i)
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];

and the wrong conversion is happening here. I checked it byte by byte.

Some conversion examples:

NSData: <00250045 044f04a4 00000000 00000000 00000000> Hex String: 00240043043d0493000000000000000000000000

NSData: <00240043 043d0493 00000000 00000000 00000000> Hex String: 002300450435049a000000000000000000000000

NSData: <00230045 0435049a 00000000 00000000 00000000> Hex String: 00250045044e04a9000000000000000000000000

NSData: <00250045 044e04a9 00000000 00000000 00000000> Hex String: 00250043043b0497000000000000000000000000

Is there something wrong with the implementation?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kevin
  • 561
  • 1
  • 7
  • 20
  • 1
    Are you sure the issue is not in your code? It seems that "Hex String" is the same as the next NSData... – Michał Ciuba Nov 20 '14 at 13:34
  • Check this question http://stackoverflow.com/questions/7520615/how-to-convert-an-nsdata-into-an-nsstring-hex-string I think it is exactly what you need. [1]: – Monicka Nov 20 '14 at 14:13
  • I can't figure out the source of the problem... I've used two snippets of code the one mentioned in the description and the one you are referring to. These two solutions have different outputs and always different from the NSData. – Kevin Nov 20 '14 at 15:35

1 Answers1

0

It works for me:

    NSMutableString *hexString = [[NSMutableString alloc] init];

    char buffer;
    for (NSInteger i = 0; i < data.length; ++i){
        [data getBytes:&buffer range:NSMakeRange(i, 1)];
        [hexString appendString:[NSString stringWithFormat:@"%02hhx", buffer]];
    }
mityaika07
  • 652
  • 5
  • 14