How to Set Range of Bits in Given Number in C with Example Code




// StringTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"
#include "stdlib.h"

//#define SETBIT(num, start_bit_pos, end_bit_pos) (num) | ((1<<(((end_bit_pos)-(start_bit_pos))+1))-1)<<((start_bit_pos)-1)
#define SETBIT(n,a,b) (n | (((((1 << (a + 1 - b)) - 1)) << (b))))

void printbin(int pnum){ 
 
    if(pnum != 0)
    {
        printbin(pnum >> 1);
     
        if (pnum & 1){
        printf("1");
        }
        else{
        printf("0");
        }
    }
    else{
     
    } 
    //    pnum >>= 1;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int num = 0x10;
    int startPos = 0;
    int endPos = 3;

    printf("Before Number = ");
    int printnum = num;
    printbin(printnum);
    printf("\n");

    /*while (printnum) {
 
        if (printnum & 1){
        printf("1");
        }
        else{
        printf("0");
        }

        printnum >>= 1;
    }
    printf("\n");*/

    int mask = ((((1 << (endPos + 1-startPos)) -1)) << (startPos));
    printf("Mask for Number = ");
    printbin(mask);
    printf("\n");

    /*printnum = mask;
    while (printnum) {
 
    if (printnum & 1)
        printf("1");
    else
        printf("0");

        printnum >>= 1;
    }
    printf("\n");*/

    num = SETBIT(num, endPos, startPos);
    printf("After Number = ");
 
    printbin(num);
    printf("\n");

    /*printnum = num;
    while (printnum) {
 
    if (printnum & 1)
        printf("1");
    else
        printf("0");

        printnum >>= 1;
    }
    printf("\n");*/ 

    getch();


    return 0;
}


Related Post:

Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...