博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swap bits in a given number
阅读量:4150 次
发布时间:2019-05-25

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

reference: 

Problem Definition:

Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.

Solution:

We need to swap two sets of bits. XOR can be used in a similar way as it is used to . Following is the algorithm.

1) Move all bits of first set to rightmost side   set1 =  (x >> p1) & ((1U << n) - 1)Here the expression (1U << n) - 1 gives a number that contains last n bits set and other bits as 0. We do & with this expression so that bits other than the last n bits become 0.2) Move all bits of second set to rightmost side   set2 =  (x >> p2) & ((1U << n) - 1)3) XOR the two sets of bits   xor = (set1 ^ set2) 4) Put the xor bits back to their original positions.    xor = (xor << p1) | (xor << p2)5) Finally, XOR the xor with original number so    that the two sets are swapped.   result = x ^ xor

Code:

int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n){    /* Move all bits of first set to rightmost side */    unsigned int set1 =  (x >> p1) & ((1U << n) - 1);     /* Moce all bits of second set to rightmost side */    unsigned int set2 =  (x >> p2) & ((1U << n) - 1);     /* XOR the two sets */    unsigned int xor = (set1 ^ set2);     /* Put the xor bits back to their original positions */    xor = (xor << p1) | (xor << p2);     /* XOR the 'xor' with the original number so that the        two sets are swapped */    unsigned int result = x ^ xor;     return result;}

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

你可能感兴趣的文章
虚拟机 CentOS7/RedHat7/OracleLinux7 配置静态IP地址 Ping 物理机和互联网
查看>>
Jackson Tree Model Example
查看>>
常用js收集
查看>>
如何防止sql注入
查看>>
springmvc传值
查看>>
在Eclipse中查看Android源码
查看>>
Android使用webservice客户端实例
查看>>
[转]C语言printf
查看>>
C 语言学习 --设置文本框内容及进制转换
查看>>
C 语言 学习---判断文本框取得的数是否是整数
查看>>
C 语言 学习---ComboBox相关、简单计算器
查看>>
C 语言 学习---ComboBox相关、简易“假”管理系统
查看>>
C 语言 学习---回调、时间定时更新程序
查看>>
C 语言 学习---复选框及列表框的使用
查看>>
第十一章 - 直接内存
查看>>
JDBC核心技术 - 上篇
查看>>
一篇搞懂Java反射机制
查看>>
Single Number II --出现一次的数(重)
查看>>
Palindrome Partitioning --回文切割 深搜(重重)
查看>>
对话周鸿袆:从程序员创业谈起
查看>>