Brett
Brett

Reputation: 12007

Objective-C - How to convert a uchar to a string of bits

I have a scenario where I have a uchar variable and I need to get its representative bits (in any form: string, bit array, array of bools, array of 1 and 0 ints, anything).

I've been searching for how to do this in Objective-C all morning with no luck.

Does anyone have any pointers on how to do this?

Upvotes: 0

Views: 108

Answers (1)

FreeNickname
FreeNickname

Reputation: 7764

uchar getBit(uchar value, int bitIndex)
{
    return value & (1<<bitIndex);
}

NSString *bitsFromUchar(uchar value)
{
    NSMutableString *bits = [[NSMutableString alloc] init];
    for (int i = 7; i >= 0; --i)
    {
        [bits appendString:(getBit(value, i)?@"1":@"0")];
    }
    return bits;
}

Upvotes: 1

Related Questions