Ive been having trouble where the segmentation fault is in my code. I am trying to make a function that converts decimal numbers into hex numbers.
Also if I was to use: 15&15 would the number be 1111 or 15?
Here is my code:
#include
#include
#include
char *to_hex(int n);
main(){
int dec;
printf("-> ");
scanf("%d",dec);
printf(to_hex(dec));
}
char *to_hex(int n){
char *array = malloc(sizeof(int)*2+8);/*makes array*/
int i;
int index=0;/*used for storing into array*/
for(i=28;i>-1;i=i-4){/*mask and compare 8 times*/
int shift=n>>i;/*right shift*/
int mask=shift&15;/*masks*/
if (mask<10){
*(array+index)=(char)mask;
index++;
}
else{
switch(mask){
case 10:
*(array+index)='a';
index++;
break;
case 11:
*(array+index)='b';
index++;
break;
case 12:
*(array+index)='c';
index++;
break;
case 13:
*(array+index)='d';
index++;
break;
case 14:
*(array+index)='e';
index++;
break;
case 15:
*(array+index)='f';
index++;
break;
}
}
}
*(array+index)='\0';
return array;
}
I think the : int mask : would equal 15 and not 1111 am I correct? Thanks