1

I have NSData and i would like to parse it by bytes. Here is an example. data is <8283010c ec4f483f 0d00000c 0c0f2840 >

I would like to pass 8 bytes to each object i create (8283010c ec4f483f for first object,0d00000c 0c0f2840 for the second) , and then parse those each bytes like this.

  //  First byte > Action = 82
  //  2nd and 3rd byte > Status = 83 01
  //  4,5,6,7 byte > Time = 0c ec 4f48
  //  8 byte > Number = 3f

How could i parse NSData to such structure, what types should i use for my variables (Action)?

unsigned char aBuffer[8];
[data getBytes:aBuffer length:8];

Tried to do a little test in such way, but NSLog prints aBuffer with strange symbols, instead of byte values.

Datenshi
  • 1,191
  • 5
  • 18
  • 56
  • Well, what do you mean by "parsing"? In this context, it doesn't quite make sense. Why don't you just copy 8 bytes from `[data bytes] + offset * 8` anyway? –  Dec 21 '12 at 13:30
  • What encoding does the data use? It may be returning 4 unichar characters instead of 8 ASCII characters.You should also tell us the definition of the structure, the one you provided isn't clear. – Ramy Al Zuhouri Dec 21 '12 at 13:34
  • There is no encoding for data. It's raw data. It would be great if i could convert this data to like NSString somehow. H2CO3 could you write a simple example on how to do this, or point me where could i learn this. Because currently this is a dark forest to me with no light. – Datenshi Dec 21 '12 at 13:36
  • @Datenshi Have you ever used `printf()`? If not, have you tried reading and understanding the documentation of `NSData`? I don't think so... –  Dec 21 '12 at 13:37
  • Yes I'v tried both, your comment makes me feel kinda stupid. Your answer did help me, and that was exactly what i was asking for, thank you for your time. And sorry for not being smart enough to grasp everything without help :) – Datenshi Dec 21 '12 at 13:42

2 Answers2

3

NSLog prints aBuffer with strange symbols, instead of byte values.

Because those are the actual bytes NSData contains, and not their hexadecimal representation. If you want a hexadecimal representation, you have to format the bytes accordingly:

NSMutableString *hexRepr = [NSMutableString string];
for (int i = 0; i < 8; i++) {
    [hexRepr appendFormat:@"%02x", ((uint8_t *)[data bytes])[offset * 8 + i]];
}
0

As a follow up on @H2CO3's answer,

According to NSData docs, [data description] returns hexadecimal representation. Wouldn't that be easier?

UPDATE: Found why [data description] shouldn't be used: https://stackoverflow.com/a/9084784/58505

Community
  • 1
  • 1
pixelfreak
  • 17,714
  • 12
  • 90
  • 109