I know that to get the last digit of an integer you can do something like this:
printf("%d\n", 1105 % 10); //It will print 5
Now, what can I do to do the same thing with a binary number?
printf("%d\n", 0101 % 10); //This will print 5 as well
I know that to get the last digit of an integer you can do something like this:
printf("%d\n", 1105 % 10); //It will print 5
Now, what can I do to do the same thing with a binary number?
printf("%d\n", 0101 % 10); //This will print 5 as well
Use %2
.
The least significant digit of a binary number has the value 1, so modulo 2 is the correct choice.
But why would 0101 be interpreted as a binary number? As ooga pointed out, leading zero makes the compiler interprete your number as an octal number. Leading 1 would be interpreted as decimal.
Afterall, %2 will give you either 1 or 0 (i.e. the least significant bit of your number in binary - no matter whether your input is binary, octal, decimal or whatever).