1092 views|0 replies

6555

Posts

0

Resources
The OP
 

Add several bit manipulation functions to C language [Copy link]

There are instructions in assembly language that operate on bits directly, such as setting, resetting, inverting, testing a certain bit, etc., which are very convenient for hardware operations. Although C language also provides some bit operation methods, such as bitwise AND, bitwise OR, bitwise inversion, etc., they operate on a byte. If you want to operate on a specific bit, it is still inconvenient. The following are some functions that can imitate some bit operation functions of assembly language.

#define uchar unsigned char

/* Test whether a bit of the variable is ' 1 ', return true if it is, otherwise return false, num is the number to be tested, bit is the number of bits, its value ranges from 0 to 7 , the same below */

uchar bittest(uchar num, uchar bit)

{ if(num>>bit&0x01==1)

return 1;

else

return 0;

}

uchar bitclr(uchar num,uchar bit) /* clear a bit */

{

uchar bit_value[]={1,2,4,8,16,32,64,128};

return num&~bit_value[bit];

}

uchar bitset(uchar num,uchar bit) /* Set a bit */

{

uchar bit_value[]={1,2,4,8,16,32,64,128};

return num|bit_value[bit];

}

uchar bitcpl(uchar num,uchar bit) /* Invert a bit */

{

uchar bit_value[]={1,2,4,8,16,32,64,128};

if(num>>bit&0x01==1)

return num&~bit_value[bit];

else

return num|bit_value[bit];

}

/* The following main program demonstrates that when calling, you can directly give a value or a variable name */

void main(void)

{

fly xx=0xfe;

xx=bitset(xx,0);

printf("The set out is %x\n",xx);

printf("The clr out is %x\n",bitclr(255,0));

printf("The test out is %x\n",bittest(0xff,0));

printf("The cpl out is %x\n",bitcpl(0x00,7));

}

The above is the main program written using TC as an example. The functions are also available in other C languages.

This post is from Microcontroller MCU
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews

Room 1530, Zhongguancun MOOC Times Building, Block B, 18 Zhongguancun Street, Haidian District, Beijing 100190, China Tel:(010)82350740 Postcode:100190

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list