0

I'm looking for a general way to create a bit mask using shifts and bitwise operators and to be wary of overflow from shifting left

ex. 0x80000000 would be something like (~0 >> 31) << 31, correct me if I'm wrong

More specifically 0xAAAAAAAA and 0x55555555 is what I'm struggling with

Crowning
  • 167
  • 1
  • 2
  • 10
  • First off, you don't need to worry about overflow when using unsigned integers. Second, this sort of shifting is only practical for contiguous set bits. – EOF Oct 12 '15 at 00:03
  • Assuming a 32-bit (or greater) system, 0x80000000 == (1 << 31). – fvgs Oct 12 '15 at 00:07
  • @EOF I'm working with signed though! – Crowning Oct 12 '15 at 00:15
  • @Crowning: There is this magical contruct: `(unsigned)whateverintvariable`. – EOF Oct 12 '15 at 00:16
  • @EOF Ah thank you! I didn't know that. However, I'm not allowed to use that in my assignment and I'm kind of curious how to go about masking this alternate way – Crowning Oct 12 '15 at 00:16
  • @hexturtle that's how I originally did it, but I modified it so it could work in an environment where shifting left 1 << 31 is considered undefined to the C Standard – Crowning Oct 12 '15 at 00:17
  • @Crowning: You basically *have to* cast. Right-shifting a negative signed integer is implementation-defined, and left-shifting it is **undefined**. – EOF Oct 12 '15 at 00:20

1 Answers1

0
printf("0x%08x\n",  (~0 << 31));
unsigned int x;
x = (~0 << 31);
x >>= 31;
x |= x << 2;
x |= x << 4;
x |= x << 8;
x |= x << 16;
printf("0x%08X\n",  x);
x = (~0 << 31);
x >>= 30;
x |= x << 2;
x |= x << 4;
x |= x << 8;
x |= x << 16;
printf("0x%08X\n",  x);

http://ideone.com/N3Yx8Z

result

0x80000000
0x55555555
0xAAAAAAAA
MrFreezer
  • 1,627
  • 1
  • 10
  • 8
  • `x = (~0 << 31); x >>= 31;` can be replaced by `x=1;` and `x = (~0 << 31); x >>= 30;` can be replaced by `x=2;` – MrFreezer Oct 12 '15 at 00:44