[ create a new paste ] login | about

Link: http://codepad.org/rZO7A594    [ raw code | output | fork ]

C, pasted on Mar 20:
/**
 * C program to toggle nth bit of a number
 */

#include <stdio.h>

int main()
{
    int num, n, newNum;

    /* Input number from user */
    /* printf("Enter any number: ");
    /* scanf("%d", &num); */

num=4;

    /* Input bit position you want to toggle 
    printf("Enter nth bit to toggle (0-31): ");
    scanf("%d", &n); */

n=2;
    /*
     * Left shifts 1, n times
     * then perform bitwise XOR with num
     */
    newNum = num ^ (2);

    printf("Bit toggled successfully.\n\n");
    printf("Number before toggling %d th bit: %d (in decimal)\n", n, num);
    printf("Number after toggling %d th bit: %d (in decimal)\n", n, newNum);

    return 0;
}


Output:
1
2
3
4
Bit toggled successfully.

Number before toggling 2 th bit: 4 (in decimal)
Number after toggling 2 th bit: 6 (in decimal)


Create a new paste based on this one


Comments: