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
  • 4,064
  • 6
  • 39
  • 69
  • 3
    `0101` is not a binary number. In fact, since it starts with a zero, it's an octal number (value 65). Your compiler may allow you to write a binary number like `101b`. – ooga Oct 23 '14 at 17:59
  • See also: [Can I use a binary literal in C or C++?](http://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c) – stakx - no longer contributing Oct 23 '14 at 19:13

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,502
  • 3
  • 16
  • 21
  • 3
    `0101` would be interpreted as an octal number. Try `printf("%d\n", 0101)`. – ooga Oct 23 '14 at 18:00
  • 2
    For those who don't want to try @ooga's snippet, it will print `65` (since `101` base 8 is 64+1=65) which explains why `0101%10` is `5`. – rici Oct 23 '14 at 18:09