开发者

Very simple masking

开发者 https://www.devze.com 2023-04-03 21:29 出处:网络
In 3 operations how can I turn a byte into a 32 bit int that matches this: 0x1fffe I can only explicitly access a byte at a time thus I start with 0xFF and then shift it.

In 3 operations how can I turn a byte into a 32 bit int that matches this:

0x1fffe

I can only explicitly access a byte at a time thus I start with 0xFF and then shift it.

I can do it using 4 operations but I cant find a way to eliminate one operation.

    int mask2 = 0xFF << 8;
    mask2 = mask2 | 0xFE;
    mask2 = mask2 + mask2;
    mask2 = mask2 | 0x02;

Any ideas?

In other words, I need a mask, 0x1FFFE to be made in开发者_JAVA技巧 3 operations while only accessing a byte at a time like the example.


Maybe this is what you want... you start with one single byte value (0xff), and you work on it with 3 bitwise operations, obtaining 0x1fffe.

int in = 0xff;
int out = in<<9 | in<<1;


shift, add, shift, that's three operations, right?

((0xff << 8) + 0xff) << 1


with two operations:

res = (1 << 17) - 2


int mask2 = 0xFF;
mask2 |= mask2 << 8;
mask2 += mask2;


How about this:

((~0xffU) >> 11) - 1

This assumes 32-bit integers...

Maybe that's better expressed as:

uint32_t x = 0xff;

x = ~x;
x >>= 11;
x -= 1;
0

精彩评论

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

关注公众号