C program to set/clear (high/low) bits of a number.

This program will set or clear (high or low) bits of a number, this operation can be performed using Bitwise OR (|) and Bitwise AND (&) operators.

High/Low (Set/Clear) bits of a number using C program

/* C program to set and clear bits of a number.*/

#include <stdio.h>

int main()
{

    unsigned int num = 0x0C;

    /*set 0th and 1st bits*/
    num |= (1 << 0); /*set 0th bit*/
    num |= (1 << 1); /*set 1st bit*/

    printf("\nValue of num = %04X after setting 0th and 1st bits.", num);

    /*clear 0th and 1st bits*/
    num &= ~(1 << 0); /*set 0th bit*/
    num &= ~(1 << 1); /*set 1st bit*/

    printf("\nValue of num = %04X after clearing 0th and 1st bits.", num);

    return 0;
}

Output:

    Value of num = 000F after setting 0th and 1st bits.
    Value of num = 000C after clearing 0th and 1st bits.

C Bitwise Operators Programs »



Related Programs



Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.