Results 1 to 3 of 3
  1. #1
    jamgor is offline Member
    Join Date
    Jun 2013
    Posts
    12
    Rep Power
    0

    Default Checking for an even\odd number by using bitshifting?

    Is there any way to do this?

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    2,947
    Rep Power
    4

    Default Re: Checking for an even\odd number by using bitshifting?

    You don't need to shift bits but you can test them. Just check to see if the low order bit is set or not. If it is set, the number is odd, if it is not set, the number is even.

    Java Code:
    int value = 23;
    if ((value & 1) == 1) {
        System.println(value + " is odd\n");
    } else
       System.println(value + " is even\n");
    }
    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    wfsteadman is offline Member
    Join Date
    Jan 2013
    Location
    Texas
    Posts
    45
    Rep Power
    0

    Default Re: Checking for an even\odd number by using bitshifting?

    Quote Originally Posted by jamgor View Post
    Is there any way to do this?
    You can use the modulus operator % which so when a number is divided by 2 if the remainder is 0 then it is an even number, else it is an odd number.
    Java Code:
     if ((24 % 2) == 0)  // % is modulus operator
          print out 24 is even
        else
          print out 24 is not even

Similar Threads

  1. Replies: 1
    Last Post: 05-08-2013, 07:19 PM
  2. Replies: 8
    Last Post: 01-21-2012, 01:14 AM
  3. Dice help. posting the number of times a number is rolled.
    By cookiejarvus in forum New To Java
    Replies: 13
    Last Post: 12-04-2011, 11:08 PM
  4. Bitshifting doesn't shift bits?
    By Skiller in forum New To Java
    Replies: 19
    Last Post: 03-02-2011, 09:30 AM
  5. Printing the Number of Times a Number in a Range Shows up
    By space4rent00 in forum New To Java
    Replies: 1
    Last Post: 02-05-2010, 10:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •