How to save multiple small integers in one integer via bit shifting in Objective C

85 views Asked by At

There are several lists of items. The number of the lists < 8. The number of items in any list < 16. User can select one item in each list. So we have a sequence of integers. For example: 9, 0, 12, 4.

There are any easy way to store user selection in one Integer (32 or 64) and reading it from there?

May be you know the more optimal way to store a sequence of 4-bit integers?

Thanks!

1

There are 1 answers

0
Artur Bortsov On
+ (NSArray *)arrayFromLongint:(uint32_t)longint {
    uint8_t shortint;
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (uint8_t i = 0; i < 32; i = i + 4) {
        shortint = longint >> i & 15; // 15 is 00001111 in binary
        [array addObject:[NSNumber numberWithUnsignedShort:shortint]];
    }
    return array;
}

+ (uint32_t)longintFromArray:(NSArray *)array {
    uint8_t shortint, itemIndex = 0;
    uint32_t longint = 0;
    NSNumber *item;
    for (uint8_t i = 0; i < 32; i = i + 4) {
        if ([[array objectAtIndex:itemIndex] isKindOfClass:[NSNumber class]]) {
            item = [array objectAtIndex:itemIndex];
            shortint = [item unsignedShortValue] & 15; // 15 is 00001111 in binary
            longint = longint | shortint << i;
        }
        itemIndex++;
    }
    return longint;
}