开发者

How to get memory address in C and output it?

开发者 https://www.devze.com 2023-02-07 12:14 出处:网络
I need to get memory address and bits of index then I need to o开发者_高级运维utput index of the memory address. Can anyone help?Given any variable in C, you can get its address using the \"address-of

I need to get memory address and bits of index then I need to o开发者_高级运维utput index of the memory address. Can anyone help?


Given any variable in C, you can get its address using the "address-of" operator &:

int x;
int* addressOfX = &x;

You can print out addresses using the %p specifier in printf:

printf("%p\n", &x); // Print address of x

To access individual bits of an integer value, you can use the bitwise shifting operators, along with bitwise AND, to shift the bit you want to the proper position and then to mask out the other bits. For example, to get the 5th bit of x, you can write

int x;
int fifthBit = (x >> 4) & 0x1;

This shifts down the number 4 bits, leaving the fifth bit in the LSB spot. ANDing this value with 1 (which has a 1 bit in the lowest spot and 0 bits everywhere else) masks out the other bits and returns the value. For example:

int x = 31; // 11111
prtinf("%d\n", (x >> 4) & 0x1); // Prints 1


This worked for me ;)

  // uses :: head
  // ----------------------------------------------
     #include <stdio.h>
  // ----------------------------------------------


  // func :: main
  // ----------------------------------------------
     int main()
     {
        void *fooz = "bar";
        char addr[64];

        sprintf(addr, "%p", &fooz);

        // do some stuff with `addr`, or not :)
        puts(addr);

        return 0;
     }
  // ----------------------------------------------

Prints out something like: ~> 0x7ffdfb91d698

0

精彩评论

暂无评论...
验证码 换一张
取 消