码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-02-22 23:28:51      阅读:409      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!