Search code examples
chexunsigned-integer

Convert hex scanned (scanf) from an unsigned int array into decimal


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 .


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.