博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swap all odd and even bits
阅读量:4151 次
发布时间:2019-05-25

本文共 1189 字,大约阅读时间需要 3 分钟。

reference: 

Problem Definition:

Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43 (00101011). Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side.

Solution:

Let the input number be x
1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA.The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and all odd bits as 0.
2) Get all odd bits of x by doing bitwise and of x with 0x55555555.The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0.
3) Right shift all even bits.
4) Left shift all odd bits.
5) Combine new even and odd bits and return.

Code:

unsigned int swapBits(unsigned int x){    // Get all even bits of x    unsigned int even_bits = x & 0xAAAAAAAA;     // Get all odd bits of x    unsigned int odd_bits  = x & 0×55555555;     even_bits >>= 1;  // Right shift even bits    odd_bits <<= 1;   // Left shift odd bits    return (even_bits | odd_bits); // Combine even and odd bits}

转载地址:http://zexti.baihongyu.com/

你可能感兴趣的文章
九度:题目1012:畅通工程
查看>>
九度:题目1017:还是畅通工程
查看>>
九度:题目1034:寻找大富翁
查看>>
第六章 背包问题——01背包
查看>>
51nod 分类
查看>>
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
性能扩展问题要趁早
查看>>
MySQL-数据库、数据表结构操作(SQL)
查看>>
OpenLDAP for Windows 安装手册(2.4.26版)
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
JSP的内置对象及方法
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>