C language bitwise inversion and binary output functions

Source: Internet
Author: User
# Include <stdio. h>

// Bit_reverse: 32-digit bitwise inversion Function
//
Purpose: reverse a 32-bit integer by bit, that is, convert 1st bits to 32nd bits, and convert 2nd bits to 31st bits.
// Algorithm Implementation: The first line of code is the exchange of parity. The second act is the exchange of two parity units. The third act is the exchange of four parity units; the fourth behavior is an octal unit, where the parity unit is exchanged. the last row is a hexadecimal unit, and the parity unit is exchanged. So far, 32-bit inversion is complete, and the algorithm is complete.

Unsigned int bit_reverse (unsigned int N)
{
N = (n> 1) & 0x55555555) | (n <1) & 0 xaaaaaaaa );
N = (n> 2) & 0x33333333) | (n <2) & 0 xcccccc );
N = (n> 4) & 0x0f0f0f) | (n <4) & 0xf0f0f0f0 );
N = (n> 8) & 0x00ff00ff) | (n <8) & 0xff00ff00 );
N = (n> 16) & 0x0000ffff) | (n <16) & 0xffff0000 );

Return N;
}

// Bit_num: Find the first bit = 1 in the 32-digit descending order.
// Implementation: right shift by bit
Unsigned int bit_num (unsigned int N)
{
Int I;
Int Len = sizeof (n) <3;
For (I = len-1; I> = 0; I --)
{
If (n> I)
Return I;
}

Return 0;
}

// Printf_binary: returns an integer in binary format.
// Implementation: right shift by bit
Void printf_binary (unsigned int N)
{
Int I;
For (I = 31; I> = 0; I --)
{
Printf ("% d", (N & (1 <(I + 1)-1)> I )? 1-0 );
If (I % 8 = 0)
Printf ("");
}
}

Int main ()
{
Int I;
Int num = 0 xffaa;
Int res;
Printf ("0x % 08x:", num );
Printf_binary (Num );
Printf ("\ n ");
Res = bit_reverse (Num );
Printf ("0x % 08x:", Res );
Printf_binary (RES );
Printf ("\ n ");

For (I = 0; I <32; I ++)
{
Num = 1 <I;
Printf ("bit_num (0x % 08x) = % 2D \ n", num, bit_num (Num ));
}

While (1)
{
Printf ("\ ninput num :");
Scanf ("% d", & num );
Printf_binary (Num );
}

Return 0;
}

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.