20 - WAP to Print Bit's using Bitwise LSB in C
This Program prints the Value of a Bit's can taking consideration of the Positing of the Bit's.
#includeint main() { //variable declaration int number, value, pos1, pos2, bit, result; char choice; do { //reading the first number from the user printf ("Enter a number that you want to change with bits of value : "); scanf ("%d", &number); //reading a number from the user printf ("Enter the number from which you want to extract bits : "); scanf ("%d", &value); //reading first position from the user printf ("Enter the First Position : "); scanf ("%d", &pos1); //reading the second position from the user printf ("Enter the Second Position but must be less than First Position : "); scanf ("%d", &pos2); getchar(); //checking that first position is higher than second or not if (pos2 >= pos1) { printf ("Position Enterd is Invalid, Try Again!\n"); } //if there is no error with position entered then this will continue else { //expression for noofbits tobe check bit = pos1 - pos2 + 1; //extracting bits from value starting from lsb value = (value & ((1 << bit)- 1 ) << pos2 ); //clearing bit position in number based on the position u entered number = number & ~(((1 << bit ) - 1) << pos2 ); //the cleared positon in number is filled with extracted bits result = number | value; // printing the number in decimal format printf ("The Number is : %d", result); } //this is to run the program again printf ("\n To Continue press ['Y'/'n'] : "); choice = getchar(); getchar(); }while (choice == 'y' || choice == 'Y' ); return 0; }
Program Output:
Post a Comment