Why do address pointers to integers have 8 symbols, and integer binary address locations have 8 bits?

StackOverflow https://stackoverflow.com/questions/23480111

  •  16-07-2023
  •  | 
  •  

Question

I have wrote a code (shown below) that stores the integer 0 to an arbitrary memory location, and then prints the pointer to this memory location and the binary address of this memory location.

The binary memory address in 8 bits long, which I did not expect. I have 4Gb of ram, so surely if the integer is stored in this ram, you will need a lot more than 8 bits to uniquely address a cell(byte) in this ram? Even more confusingly the pointer is 8 symbols long. If the binary address is 8 bits long surely you only need 2 symbols for the pointer to this address?

So why does the address pointer have 8 symbols, and integer binary address locations have 8 bits?

I have taken the byte_to_binary function from this SE Question. Im still a beginner so my code may not be correct.

#include "stdafx.h"
#include <stdio.h>
#include <string.h>     /* strcat */
#include <stdlib.h>     /* strtol */


const char *byte_to_binary(int x)  //code taken from-https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}

int main(void) //my code starts here
{
    int A = 0;
    int *Ap = &A;
    unsigned int number = (unsigned int)Ap;

    printf("%s \t %d \n \n","int Value",A); //prints the value stored in Ap as an integer

    printf("%s \t %s \n \n","bin Value",byte_to_binary(A)); //prints the value stored in Ap as a binary number 

    printf("%s \t %p \n \n","adress Pointer",Ap); //prints pointer address as pointer type

    printf("%s \t \t %s \n \n","adress",byte_to_binary(number)); //prints pointer address in binary


    return 0;
}

This outputs:

int Value        0

bin Value        00000000

adress Pointer   003FFE1C

adress           00011100

Press any key to continue . . .
Was it helpful?

Solution

It's your binary conversion function that is not working correctly.

 0x003FFE1C 

is 00000000001111111111111000011100

You're not going far enough with the bits.

You might want to do a

 sizeof (Ap) 

to see how many bits you need. (Here 32)

You should change your loop index so that it is the bit position rather than the shifted value, otherwise you are risking overflow.

for (int ii = 31 ; ii >= 0 ; -- ii)
{

   if (x & (1 << ii) != 0)
      strcat (b, "1) ;
   else
      strcat (b, "0") ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top