anoymous_coder
anoymous_coder

Reputation: 3

How can I do bit operations with a pointer as per the following code?

char *function(struct devices *address, int nbytes)
{  
    if((1<<0)|address)
    {
      printf("Hello World");
    }
    else if((1<<2)|address)
    {
      printf("Hello World");
    }
 
  return 0;
 
}

However the problem lies wherein I am unable to use the address since its a pointer, so can someone tell me how I can set the address accordingly so that bit operations can be performed? Or do I manually define the address inside the code itself?

Upvotes: 0

Views: 80

Answers (2)

klutt
klutt

Reputation: 31366

This does not sound like a good idea, but you could do something like this:

#include <stdint.h>

char *function(struct devices *address, int num_bytes)
{  
    uintptr_t x = (uintptr_t) address;

    if((1<<0)|x)
    {
      printf("Hello World");
    }
    else if((1<<2)|x)

But unless you're 100% sure about what you're doing, avoid this. Don't assume certain numeric properties for memory addresses. This can cause really iffy and hard traced bugs.

And note that an expression on the type x|y will be evaluated as true as long as either of x and y is non-zero. You probably want to do something like (1<<0)&x instead.

Upvotes: 2

Lundin
Lundin

Reputation: 213799

Convert to uintptr_t from stdint.h, do all bitwise arithmetic on that type, then convert back to the pointer type when you are done.

But of course, converting from some integer to a pointer type can cause all manner of problems if you don't know what you are doing, such as misaligned access and/or the compiler doing bananas code optimizations. Tread carefully.

Upvotes: 0

Related Questions