Reputation: 12631
#include<stdio.h>
int main(int argc,char* argv[]){
int hex;
printf("\n argc : %d argv[1] : %s \n",argc,argv[1]);
hex = argv[1];
printf("\n hex : %x \n",hex);
return 0;
}
o/p:
[root@ld]# ./a.out 343ed4
argc : 2 argv[1] : 343ed4
hex : 9e1a4aa8
I wanted to store the hex value got from the command line argument and store it on the integer. The above program , when stored the hex value gives a different result from the user given value. Cant use atoi too as it would cut of the alphabets after the numbers. How to store the hex entered in the command line arguments into an integer.
Upvotes: 2
Views: 1620
Reputation: 8830
as per dasblinkenlight
You need to do this:
sscanf(argv[1], "%x", &hex);
BUT
sscanf returns the number of arguments (as in %x) successfully parsed. So I would add a check for it to be 1. If it isn't they entered something that could be parsed to hex.
printf("\n argc : %d argv[1] : %s \n",argc,argv[1]);
if (sscanf(argv[1], "%x", &hex)==1)
printf("\n hex : %x \n",hex);
else
printf("\nargv[1] is not a valid hex value.");
if you don't check the return value you will not pick up the point of failure in your code.
sscanf can be used to match patterns and extract the variable values from them like a date import for example:
int day, month, year;
int count = sscanf (inputstr, "%d/%d/%d", &day, &month, &year );
if (count!=3)
printf("bad date value");
Upvotes: 4
Reputation: 726809
This is incorrect:
hex = argv[1];
The compiler should have warned you about assigning a char*
to int
, because argv[1]
is a string representation of a hex number (i.e. {'3','4','3','e','d','4','\0'}
), not a hex number itself.
You need to do this:
sscanf(argv[1], "%x", &hex);
sscanf
parses the hex number for you, and stores the result in hex
.
Upvotes: 5