Reading NSNumber from NSData

I am new to Objective-C (and C itself) and should consume NSDatafrom HTTP output. I have never worked with byte arrays or worried about problems with small / large ends, and tried a bit to write the following method for reading NSNumberwith the specified length from this NSData.

- (NSNumber *)readNumberWithLength:(NSUInteger)length
{
    Byte k[length];
    [data getBytes:k range:NSMakeRange(offset, length)]; // big endian byte array representing a number
    offset += length;

    NSNumber *number;
    if (length==4) {
        number = [NSNumber numberWithUnsignedInt:CFSwapInt32BigToHost(*(uint32_t *)k)];
    } else if (length==2) {
        number = [NSNumber numberWithUnsignedShort:CFSwapInt16BigToHost(*(uint16_t *)k)];
    } else if (length==1) {
        number = [NSNumber numberWithUnsignedChar:*(uint8_t *)k];
    } else if (length==8) {
        number = [NSNumber numberWithUnsignedLongLong:CFSwapInt64BigToHost(*(uint64_t *)k)];
    } else {
        number = [NSNumber numberWithInt:0];
    }

    return number;
}

I have NSData *dataand NSUInteger offsetare declared as instance variables.

Is this code correct? What should I worry about? I have not tested it on the device itself (only on the simulator), and it seems to work fine for me. Do you have any comments about this?

Thanks!

+3
source share
1

.

.

- , - , HTTP-, . , , , , . (, , , -HTTP- - , ).

100 , , HTTP, . , ( HTTP ).


: . - , .

:

  • , / , ( - - ).

  • case if/else if/else if/else. , ...

  • ... length, , , . , ?

+2
source

Source: https://habr.com/ru/post/1722020/