首页 > 编程语言 > 详细

[转载] C++位运算:将一个4字节整数的二进制表示中的001替换为011

时间:2016-02-22 23:27:25      阅读:558      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <assert.h>


/**
* Key:
* * get someone bit: num & (mode1bit<<N)
* * check a few bits: num & (mode3bit<<shift) == What
*/
int replace(int num)
{
    unsigned int mode3bit = 7;
    unsigned int mode1bit = 1;
    int shift = 0;
    int result = 0;
    while (shift < 32)
    {
        while (shift < 32 && (num & (mode3bit<<shift)) != (1<<shift))
        {
            result += (num & (mode1bit<<shift));
            shift++;
        }
        if (shift >= 32)
        {
            break;
        }
        else if (32 - shift < 3)
        {
            result += (num & (mode3bit<<shift));
            break;
        }
        result += (3<<shift);
        shift += 3;

    }
    return result;
}

 

[转载] C++位运算:将一个4字节整数的二进制表示中的001替换为011

原文:http://www.cnblogs.com/lifeinsmile/p/5208464.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!