I read that you can't do bitmasks on pointers, how come you can't do bitwise operations on pointers?
Is there any way to achieve the same effect?
Does the same apply to C++?
In the C programming language, operations can be performed on a bit level using bitwise operators. Bitwise operations are contrasted by byte-level operations which characterize the bitwise operators' logical counterparts, the AND, OR, NOT operators.
The Bitwise Not operation treats the sign bit as it would any other bit. If the input for a pixel location is negative, the output is negative; if the input is positive, the output is positive. If the input is a multiband raster, the output will be a multiband raster.
The Bitwise Operator in C is a type of operator that operates on bit arrays, bit strings, and tweaking binary values with individual bits at the bit level. For handling electronics and IoT-related operations, programmers use bitwise operators. It can operate faster at a bit level.
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits.
The reason you can't do bitwise pointer operations is because the standard says you can't. I suppose the reason why the standard says so is because bitwise pointer operations would almost universally result in undefined or (at best) implementation-defined behavior. So there would be nothing you could do that is both useful and portable, unlike simpler operations like addition.
But you can get around it with casting:
#include <stdint.h> void *ptr1; // Find page start void *ptr2 = (void *) ((uintptr_t) ptr1 & ~(uintptr_t) 0xfff)
As for C++, just use reinterpret_cast
instead of the C-style casts.
It's disallowed because the semantics aren't really well defined. You can certainly do it, though. Just cast to uintptr_t
, do the operations and then cast back into a pointer type. That will work in C++, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With