错误地更新位的字段 [英] Updating fields of bits incorrectly

查看:45
本文介绍了错误地更新位的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决一个问题.它说,

I'm trying to solve a question. It says,

将新变量初始化为值17512807u.

Initialize a new variable to the value 17512807u.

假设我们像往常一样将位从0降到最低有效位(在 右)到31(最重要,在左侧).通过更新位18 21的整数值为8,位10到14的值为17 (十进制).将结果值打印为八位十六进制 显示所有数字的数字.

Assume we number the bits as usual from 0 as least significant (on the right) to 31 (most significant, on the left). Update bits 18 through 21 with the integer value 8 and bits 10 through 14 with value 17 (decimal). Print the resulting value as an eight digit hexadecimal number to show all of the digits.

这是我想出的代码:

#include <stdio.h>

int main(){
    int value = 17512807u;
    int L = 21; // starting left position
    int R = 18; // starting right position

    int mask = (1 << (L - R + 1) - 1) << R; 
    int newField = (8 << R) & mask; // integer value 8, shifting to right
    int newValue = value & (~mask); // remove range of bits
    value = newField | newValue; // update range of bits

    L = 14;
    R = 10;

    mask = (1 << (L - R + 1) - 1) << R;
    newField = (17 << R) & mask;
    newValue = value & (~mask);
    value = newField | newValue;

    printf("%08x\n", value);
}

我得到的答案是012b7d67

The answer I get is 012b7d67

但是,我被告知这是错误的答案.我不知道正确的答案是什么.

However, I am told this is the incorrect answer. I do not know what the correct answer is.

推荐答案

int mask = ((1 << (L - R + 1)) - 1) << R;

这篇关于错误地更新位的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆