type c pin定义_定义宏以在C中切换一些PIN

type c pin定义

Given PIN (value) and a bit to be toggled, we have to toggle it using Macro in C language.

给定PIN(值)和要切换的位,我们必须使用C语言中的Macro进行切换。

To toggle a bit, we use XOR (^) operator.

为了切换一点,我们使用XOR(^)运算符。

Macro definition:

宏定义:

    #define TOGGLE(PIN,N) (PIN ^=  (1<<N))


Here,

这里,

  • TOGGLE is the Macro name

    TOGGLE是宏名称

  • PIN is the value whose bit to be toggled

    PIN是要切换其位的值

  • N is the bit number

    N是位数

Example:

例:

#include <stdio.h>

#define TOGGLE(PIN,N) (PIN ^=  (1<<N))

int main(){
	
	unsigned char val = 0x11;
	unsigned char bit = 2;
	
	printf("val = %X\n",val);
	
	//TOGGLE bit number 2
	TOGGLE(val, bit);
	printf("Aftre toggle bit %d first  time, val = %X\n", bit, val);

	//TOGGLE bit number 2 again
	TOGGLE(val, bit);
	printf("Aftre toggle bit %d second time, val = %X\n", bit, val);
	
	return 0;	
}

Output

输出量

    val = 11
    Aftre toggle bit 2 first  time, val = 15
    Aftre toggle bit 2 second time, val = 11

Explanation:

说明:

  • Initially val is 0x11, its binary value is "0001 0001".

    最初val为0x11 ,其二进制值为“ 0001 0001”

  • In this example, we are toggling bit number 2 (i.e. third bit of the val), initially bit 2 is 0, after calling TOGGLE(val, bit) first time, the bit 2 will be 1. Hence, the value of val will be "0001 0100" – thus, the output will be 0x15 in Hexadecimal.

    在此示例中,我们切换第2位(即val的第三位),最初的bit 2为0,在第一次调用TOGGLE(val,bit)之后 ,第2位将为1。因此, val的值将为为“ 0001 0100” –因此,输出将为十六进制的0x15

  • Now, the bit 2 is 1, after calling TOGGLE(val, bit) again, bit 2 will be 0 again, hence the value of val will be "0001 0001" – thus, the output will be 0x11 in Hexadecimal.

    现在,第2位为1,在再次调用TOGGLE(val,bit)之后,第2位将再次为0,因此val的值将为“ 0001 0001” –因此,输出将为十六进制的0x11

翻译自: https://www.includehelp.com/c-programs/define-macro-to-toggle-a-bit-of-a-pin-in-c.aspx

type c pin定义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值