gpt4 book ai didi

c - 按位与运算程序执行问题

转载 作者:行者123 更新时间:2023-11-30 16:45:42 25 4
gpt4 key购买 nike

下面是一个程序,我试图在其中重置十六进制数的特定位。位位置、要重置的位数和十六进制值都是用户输入。

头文件

#pragma once

int bit0(int i,unsigned int RegA,unsigned int RegB,int s[]);

C 文件

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "targetver.h"
#include "bit.h"

int bit0(int i,unsigned int RegA,unsigned int RegB,int s[])
{
unsigned int j=0;
unsigned int K=0;
unsigned int L=0;

printf("\nThe bit is at s[0] is %x\n", s[0]);

for (j=0; j<i; j++)
{
K = (1 << s[j]);
L = ~K;
RegB = RegA & ~L;
printf("\nThe bit is %x\n", RegB);

if (RegB | 0)
{
RegB = RegB & ~ (1 << s[j]);
}
else
{
RegB;
}
}

printf("\nThe new reset bit is %x\n", RegB);

_getch();
return 0;
}

主文件

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "iostream"
#include "targetver.h"
#include "bit.h"

int main()
{
int i=0;
int j=0;
int s[35]={0};
unsigned int RegA = 0;
unsigned int RegB = 0;

printf("Enter the hexa decimal value to be reset ");
scanf_s("%x", &RegA);
printf("Entered hexa decimal value is %x ", RegA);

printf("\nHow many decimal places needs to be reset (0-31) ?");
scanf_s("%d", &i);

printf("Enter the decimal places that needs to be reset ");

for (j=0; j<i; j++)
{
scanf_s("%d", &s[j]);
}

///// check the entered hex value on those decimals places as bit 0 or bit 1

bit0(i,RegA,RegB,s);

_getch();
return 0;
}

我正在使用 Visual Studio 编译并运行执行上述代码。

问题出在 C 文件的 RegB = RegA & ~L; 行上。 AND 运算似乎没有发生,因为我得到 0 作为 RegB 值。

程序输入:

输入要重置的十六进制值:0100 1111

输入的十六进制值为:0100 1111

需要重置多少位小数(0-31):1

输入需要重置的小数位数:1

最佳答案

当然你得到0,但那是因为 &您编写的操作(全部)正在执行。这是代码的相关部分:

    K = (1 << s[j]);
L = ~K;
RegB = RegA & ~L;
printf("\nThe bit is %x\n", RegB);

if (RegB | 0)
{
RegB = RegB & ~ (1 << s[j]);
}
else
{
RegB;
}

不过,在我们继续之前,有很多简化的机会:

  • 变量L这只会让我的事情变得复杂;我宁愿只看到~K
  • RegB | 0相当于 RegB
  • else block 不执行任何操作
  • if block 可以无条件安全地执行,也就是说,如果给定条件为 false 时执行该 block ,则不会发生任何变化。
  • 虽然您设置了K = (1 << s[j])并且之后不要更改它,稍后您可以使用表达式 (1 << s[j]) 重复自己的操作而不是仅仅说K .
  • printf()可能有一些调试实用程序,但它稍微掩盖了计算的细节

这个等效代码将更容易推理:

    K = (1 << s[j]);
RegB = RegA & K;
RegB = RegB & ~K;

此时问题应该非常清楚:无论 RegA 的值是多少是,只要s[j]介于 0 和 30 之间,* 您计算 RegB首先屏蔽掉一些RegA的位,然后屏蔽掉剩余的位。当然,结果总是0。

*因为1是一个有符号整数常量,如果实现的 int s 为 32 位宽,左移 31 位会产生超出范围的结果。就标准而言,结果行为是未定义的。最好使用无符号常量来避免此问题,即 1U .

关于c - 按位与运算程序执行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44004851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com