Search code examples
iosnsdata

Extract ints from bytes in iOS


I’m trying to construct a CMap from “FontFile2” in a PDF.

I have bytes that I know are BigEndian stored in an NSData object. I’d like to read the first 4 bytes as raw data. Then I’d like to read the following 8 bytes as 4 unsigned shorts.

Then I’d like to read the following 16 bytes as a 4 byte string followed by three unsigned longs. Then maybe a few more 4 byte strings followed by three unsigned longs.

edit

  NSData* subdata = [stream subdataWithRange:NSMakeRange(0, 4)];
    const unsigned char *bytes = [subdata bytes];
    int test = *(int*)bytes;

My failed attempt at reading the first 4 bytes as a short. It seems that breaking up the data into a bunch of subdata objects is overly complex. Their must be an easier way...

Thanks


Solution

  • Generally, if you want to read bytes, you should create an NSInteger to store the position of read bytes.

    For example, this is how you read short:

    @property NSInteger position;
    
    NSData *yourData;
    
    short extractedShort;
    [yourData getBytes:&temp range:NSMakeRange(self.position, sizeof(extractedShort))];
    self.position += sizeof(extractedShort);
    

    Read int, NSString, float, long ... value are similar