I have c program that takes in a long long
argument. When i try to convert this long to its binary representation then it turns out all wrong. But if i set a long long
variable that is equal to the value of the long long
argument then i get the correct binary representation.
int main(int argv, long long value)
{
long long i = value; // value = 2
long long e = 2;
printBits(sizeof(e), &e); // 0000000000000000000000000000000000000000000000000000000000000010
printBits(sizeof(i), &i); // 0000000000000000011111111111110000010000111010101110101000001000
return 0;
}
So as you can see above the argument retrieved through the console as input is no where near to what it should be.
printBits() is a copy paste from this solution.
Can someone clearify what is happening?
The signature of
main()
in your codeis invalid and wrong for hosted environments. The second argument is supposed to be of type
char **
. By defining theargc
equivalent aslong long
, you're trying to receive achar **
type into along long
type, which causes undefined behavior, as they are not compatible types, anyway.To put it in other words, the supplied command line arguments, are passed as pointer to strings. You need to apply proper conversion to get them back to
long long
or any other compatible type.strtoll()
is just made for that purpose.Quoting
C11
, chapter §5.1.2.2.1,and, paragraph 2,