Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you do bitwise operations on pointer in C, and is there a way around this?

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++?

like image 464
rubixibuc Avatar asked Apr 07 '13 21:04

rubixibuc


People also ask

Can you do bitwise operations in 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.

How does bitwise not work in C?

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.

Where do we use bitwise operators in C?

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.

On what can bitwise operators operate?

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.


2 Answers

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.

like image 195
Dietrich Epp Avatar answered Sep 24 '22 16:09

Dietrich Epp


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.

like image 28
Carl Norum Avatar answered Sep 24 '22 16:09

Carl Norum