Question

I'm here trying to convert 4-digit hexa into dec but didn't succeed. Here is a my code.

unsigned int array[4];                         

printf("Type in 4-digit hexa: \n");

scanf("%x", &array);

while(getchar() != '\n');

printf("Your number in dec is %u \n", array);

I don't know what's wrong with it but it just wouldn't give out the correct dec output. Like when I put in EEFF, it's supposed to give out 61183 but the program kept on printing out 65518.

Where's this number from? What's wrong with my code? I used unsigned int according to my consideration that FFFF is equals to 65385 and the range for unsigned int is 0 to 65535. There should be no problem with the range of data and I also used %u with it.

The only thing I can think of right now after I've done some searching is that this problem might has sth to do with the size of unsigned int to int or sth. I read the explanation but didn't quite understand.

I know, this might be a duplication but I'm here asking for an easier explanation of why this doesn't work. To be honest, I'm an absolutely newby for both this site and programming so please go easy on me with the coding. FYI, I don't really know anything outside of stdio.h .

Was it helpful?

Solution

You are passing a pointer, array, to printf(). There is no need for an array here, what you're trying to scan and print is a single number.

unsigned int number;

printf("Type in 4-digit hex:\n");

if (scanf("%x", &number) == 1)
  printf("Your number in dec is %u \n", number);

Also note that it's considered a good idea to check if scanf() succeeds or not, by inspecting the return value.

OTHER TIPS

You don't need an array for that:

unsigned int val;
printf("Type in 4-digit hexa: \n");
scanf("%x", &val);
printf("Your number in dec is %u \n", val);

a. print array[0], not array.

(optional) b. scan to array, not to &array.

c. what is the point of the getchar()?

No, you must input as string to a point of characters. After that, you convert to number. Ex

char *str=char[10];
int i=0,num=0;
printf("Type in 4-digit hexa: ");
scanf("%s",str);

for(i=0;str[i]!='\0';i++)
   if(str[i]>='0' && str[i]<='9') num=16*num+str[i]-'0';
   else if(str[i]>='a' && str[i]<='f') num=16*num+str[i]-'a';
   else if(str[i]>='A' && str[i]<='F') num=16*num+str[i]-'A';

printf("Dec is %d",num);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top