Converting NSdata to bytes & then converting the first n bytes to int

后端 未结 3 1807
谎友^
谎友^ 2021-02-03 16:36

I\'ve a NSData object. First I want to convert NSData object to bytes, then read the first four bytes in this NSData object and then conve

3条回答
  •  深忆病人
    2021-02-03 16:53

    Getting an int out of raw data is ambiguous: where does the data come from? What size do you want your int? Do you want them signed or unsigned? What byte ordering do you expect?

    So here is one scenario: the data you get is from a stream encoded by an external process that feeds 32-bit signed ints in big-endian order. Here's how you could do it:

    NSData *dataFromStream = functionThatReturnsNSData();
    SInt32 *signedInt32pointer = [dataFromStream bytes];
    SInt32 unSwappedInt32 = *signedInt32pointer;
    SInt32 reorderedInt32 = CFSwapInt32BigToHost(unSwappedInt32);
    

    RTFM the Byte ordering and byte swapping sections of the Memory Management Programming Guide for Core Foundation.

提交回复
热议问题