0

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
Luis Lavieri
  • 3,857
  • 6
  • 38
  • 65

1 Answers1

5

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).

jp-jee
  • 1,375
  • 3
  • 15
  • 21