Define a Macro to set Nth bit to Zero in C

Here, we will learn how to set Nth bit of a number/PIN to Zero in C programming language by using Macro?
By IncludeHelp Last updated : March 10, 2024

Macro definition

 #define SETPIN(PIN,N) (PIN &= ~(1<<N))

Here,

  • SETPIN is the Macro name
  • PIN is the value whose bit to set to zero
  • N is the bit number

Example

#include <stdio.h>

#define SETPIN(PIN,N) (PIN &= ~(1<<N))

int main(){
	
	unsigned char val = 0xFF;
	unsigned char bit = 2;
	
	printf("val = %X\n",val);
	
	//SET bit number 2 to zero 
	SETPIN(val,bit);
	printf("Aftre setting  bit %d to zero, val = %X\n", bit, val);
	
	return 0;	
}

Output

    val = FF
    Aftre setting  bit 2 to zero, val = FB

Explanation

  • In this example, initially the value of val is 0xFF that is "1111 1111" in binary.
  • To set bit number 2 (i.e. third bit) to zero, when we call macro SETPIN(val, bit), the bit number 2 will set to 0. Thus, the output will be "1111 1011" i.e. 0xFB in Hexadecimal.

C Preprocessors Programs »

Comments and Discussions!

Load comments ↻





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