Showing posts with label bitshit. Show all posts
Showing posts with label bitshit. Show all posts

Thursday, November 9, 2017

Binary Number with Alternating Bits




Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011. 



bool hasAlternatingBits(int n) {
   
    if (n == 1 || n == 2) return true;
    int mask = n << 1;
    int flag = n ^ mask;
   
    flag = (n & 0x1)?(flag & (flag+1)):(flag & (flag+2));
   
    if (flag)
        return false;
    else
        return true;
}


or


bool hasAlternatingBits(int n) {
    int mask = n >> 1;
    int flag = n + mask;
   
    if (flag&(flag+1))
        return false;
    else
        return true;
}


Sunday, September 9, 2012

program to count 1's in the given integer


Ref for Several BIT Manipulation type and techniques based Example  :

http://graphics.stanford.edu/~seander/bithacks.html

for ex :

Q 1. Write a program to count 1's in the given integer ?

Lets say we are using 32 bit  - little endian processor. User enters any integer value and we need to find the number of bit 1 in that integer.

Example: integer n =(10) base 10 equals to (0000 0000 0000 0000 0000 0000 0000 1010) base 2. so there are 2 1's bits in this . so the Output should be 2.

Program:

#include stdio.h
#include conio.h
int main()
{
      int a,b=1,c=0; //lets say a = 12
      printf("Enter the integer: ");
      scanf("%d",&a);
      while(a)
     {        
           if(a&b)
           c++;
           a=a>>1;
      }
      printf("number of 1: %d",c);
      getch();
      return 0;
}

// Note: it will change the Value of original provided integer to 0.