Question

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<stdio.h>
#include<stdlib.h>
#include<string.h>

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

Was it helpful?

Solution

You can probably avoid the segfault by changing scanf("%d",dec); to scanf("%d",&dec);, and if you want printable results, change *(array+index)=(char)mask; to *(array+index)=(char)mask+'0'; (or, better, array[index] = mask + '0';

printf(to_hex(dec)); is a bit iffy, too. Use printf("%s",to_hex(dec)); instead; it's safer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top