简体   繁体   中英

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

  • This function reads the values at the respective register address.
  • I am trying to do some operations with the bits of the address.
  • The formulae that I am following is: (1 << n) | address; wherein address is the address of register and n is the number of bits to be set.
  • An example of how I am going to run this function is (0x8,1), 0x8 is register address and 1 is nbytes.
char *function(struct devices *address, int nbytes)
{  
    if((1<<0)|address)
    {
      printf("Hello World");
    }
    else if((1<<2)|address)
    {
      printf("Hello World");
    }
 
  return 0;
 
}

  • For example Suppose I have a register address of 0x8 = 0000 1000, now lets say I wanna set the 2nd bit of this register. So, it becomes like (1<<2) | 8 (In other terms - ((0000 0001 << 0000 0010) | 0000 1000). which gives value of 0000 1100.).
  • I am using this (1 << n) | address to set the bits as per required.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM