A few bits of C language Operation function--it is convenient to use

Source: Internet
Author: User
Tags bitset bitwise

In assembly language there is direct to the operation of the instructions, such as the position, reset, bit to reverse, test one, etc., this is very convenient for hardware operation, in C language Although also provides some bit manipulation means, such as bitwise AND, bitwise OR, bitwise reverse, but they are to a byte operation, such as to a specific operation, Still inconvenient, the following gives a number of functions, can imitate the assembly language some bit operation function.

#define UCHAR unsigned char

/* Test variable whether one is ' 1 ', is return True, no return false, NUM is to be tested number, bit is the number of digits, its value 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 one/

{

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

Return num&~bit_value[bit];

}

Uchar Bitset (uchar num,uchar bit)/* Set a certain one */

{

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

return num|bit_value[bit];

}

Uchar bitcpl (uchar num,uchar bit)/* Take the opposite of a

{

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 demo, call, you can directly give the numerical value, also can give the variable name * *

void Main (void)

{

Uchar Xx=0xfe;

Xx=bitset (xx,0);

printf ("The Set is%x/n", XX);

printf ("The CLR out of IS%x/n", BITCLR (255,0));

printf ("The test out of%x/n", Bittest (0xff,0));

printf ("The CPL Out are%x/n", Bitcpl (0x00,7));

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.