Exchange odd and even digits of an integer

Source: Internet
Author: User

Problem definition:

Write a program to swap odd and even bits in an integer with as few instructions as possible (E. g, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc)

The Code is as follows. I thought about it for one night and thought it was too bad.

# Include <stdio. h> int swapoddevenbit (int x) {return (X & 0 xaaaaaaaa)> 1) | (X & 0x55555555) <1 ));} int main (INT argc, char * argv []) {int A = 171; printf ("% d \ n", swapoddevenbit (a); Return 0 ;}

171: 10101011

01010111:

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.