I was wondering if I could use a char* value to access to each byte of an int value... So I tried to use a pointer value to access the first byte of the int and a for cycle to access the other bytes of int...
Here's the code:
int char_to_bin(char* d){
int p= (int)*d;
int i=0,number=0;
if (p>=0){
do{
number+= (p%2)*(pow(10,i));
i++;
p= p/2;
}while (p>0);
}
else{
p=p *(-1);
do{
number+= (p%2)*pow(10,i);
i++;
p=p/2;
}while (p>0);
number*=-1;
}
return number;
}
long int int_to_bin(int* p){
long int j=1,number=0,number1=0,number2=0,digits;
char* c=&p;
number=char_to_bin(c);
for (j;j<(sizeof(int)/sizeof(char));j++){
number1=char_to_bin(c+j);
digits=floor(log10(abs(number1))) + 1;
number2=number1*pow(10,digits);
number=number1+number2;
}
return number;
}
int main(){
char k= 100;
char* j= &k;
int inte=100;
int *h;
h= &inte;
int c= char_to_bin(j);
printf("%d\n",c);
long int d= int_to_bin(h);
printf("%ld\n",d);
}
the function int char_to_bin(char* d)
converts a pointed char value to a binary number, and all the tests I've done on it show it works. But as I use int char_to_bin(char* d)
in int_to_bin(int* p)
something goes wrong.
Basically, int_to_bin(int* p)
should convert the first byte of the pointed int in binary, and then convert the following bytes (since char* points at one only byte) to decimal, multiply the bytes for 10^(number of digits), so that I might get a number like "000000001100100" for example but something goes wrong and the result of the function is far different from binary, plus, i have tried to put a printf("%d \n",number1)
in the int_to_bin(int* p)
function, like this:
long int int_to_bin(int* p){
long int j=1,number=0,number1=0,number2=0,digits;
char* c=&p;
number=char_to_bin(c);
for (j;j<(sizeof(int)/sizeof(char));j++){
number1=char_to_bin(c+j);
printf("%d \n",number1); //---------------here------------------
digits=floor(log10(abs(number1))) + 1;
number2=number1*pow(10,digits);
number=number1+number2;
}
return number;
}
to check the value contained in the given memory address... As far as I know, int variable types occupy 4 bytes of memory, and the sum of the content of the bytes is the value or the variable... But I get results that summed are totally different from the variable value.
Is there anything to be done to fix this, or should I just give up and try to convert the int passed int_to_bin(int* p)
into char and pass it to the char_to_bin(char* p)
function?