将一个寄存器内的值中的某连续几位(start--end)的值替换为给定的val值

思路:

a、先将替换的连续位数清零

b、将给定的值左移start位后跟所给的值相或。例如:1011 0000 101(1501)--->1011 1111 101(1533)

源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ReplaceValueToRegister(int iVal, int RegVal, int start, int end)
{
    int i;
    for(i = start; i < end; i++)
    {
        RegVal &= ~(1 << i);
    }
    RegVal |= iVal << start;

    return RegVal;
}

int main(int argc, char* argv[])
{
    int iTestVal = 1501;
    printf("Change Before, The Value is %d\r\n", iTestVal);
    iTestVal = ReplaceValueToRegister(15, 1501, 3, 7);
    printf("Change After, The Value is %d\r\n", iTestVal);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30295609/article/details/79999251
今日推荐