开发者

Bit shifting coding efficiency (i.e. neat tricks)

I'm working on a Objective-C program where I'm getting bitfields over the network, and need to set boolean variables based on those bits.

Currently I'm repr开发者_运维百科esenting the bitfields as int's, and then using bit shifting, similar to this (all the self properties are BOOL):

typedef enum {
    deleteFlagIndex = 0,
    uploadFlagIndex = 1,
    moveFlagIndex = 2,
    renameFlagIndex = 3
} PrivilegeFlagIndex;

int userFlag = 5; //for example

// this would be YES
self.delete = ((userFlag & (1 << deleteFlagIndex)) == (1 << deleteFlagIndex));
// this would be NO
self.upload = ((userFlag & (1 << uploadFlagIndex)) == (1 << uploadFlagIndex));

And this works (to the best of my knowledge) but I'm wondering - is there a more efficient concise way to code all the bit twiddling using a fancy trick/hack? I ask because I'll be doing this for a lot of flags (more than 30).

I did realize I could use this method this as well:

self.move = ((userFlag & (1 << moveFlagIndex)) > 0)

...which does reduce the amount of typing, but I don't know if there's a good reason to not do it that way.

Edit: Revised to say concise rather than efficient - I wasn't worried about execution performance, but rather tips and best practices for doing this in a smart way.


Try:

typedef enum {
    deleteFlag = 1 << 0,
    uploadFlag = 1 << 1,
    moveFlag = 1 << 2,
    renameFlag = 1 << 3
} PrivilegeFlags;

Now you can combine them using | directly.

Usually, it suffices to check against 0:

if (userFlag & deleteFlag) {
    // delete...
}


You may want to try to use bitfields and let the compiler do the optimization itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜