Reputation: 21
I have a written a code to convert a large number based on the use input to hexadecimal number. However when the result is printed, the only part of the number is converted to hexadecimal and there are other random values in the array.
for example: decimal = 1234567891012 ---- the hexa would = 00 00 00 02 00 00 00 65 00 6b 42 48 71 fb 08 44
the last four vales (71 FB 08 44
) are the correct hexadecimal value, but the others are incorrect
i am using uint8_t buf[];
Code:
int main()
{
uint8_t buf[] = {0};
long int i,a;
printf("Enter Number: ");
scanf("%d", &buf);
printf("\n");
printf("Input #: ");
/* put a test vector */
for (i = 15; i >= 0; i--)
{
printf("%02x ", buf[i]);
}
printf("\n\n");
printf("\n\n");
printf("%d\n",sizeof(buf));
system("pause");
return 0;
}
Upvotes: 0
Views: 880
Reputation: 49393
After you posted code the problems become more apparent:
First this:
uint8_t buf[] = {0};
Is no good. You need to assign a size to your array, (or make it dynamic), that's why you're getting "garbage" when you go to access the elements. For now, we can just give it an arbitrary size:
uint8_t buf[100] = {0};
That fixes the "garbage" values problem.
Second problem is your scan if is expecting a normal int
sized value: "%d"
you need to tell it a to look for a bigger values, something like:
scanf("%llu", &buf[0]);
Still, you should validate your input against the limits. Make sure what the user inputs is in the range of LONG_MAX or INT_MAX or whatever type you have.
Upvotes: 0
Reputation: 25705
Disclaimer: since you've not provided the source code, I shall assume a few things:
this happens because you've used unsigned int
to store the decimal, which is 32 bit only on your computer. Use a unsigned long
to store a decimal that big.
unsigned long decimal = 12345678901012L;
And for 16 byte decimal, use GMP Lib.
--- edit ---
You must use scanf("%lu", &decimal)
to store into a long decimal. The scanf("%d", &decimal) only copies "integer(signed)" which probably is 32 bit on your machine!
Upvotes: 1