位掩码,用于确定数字是正数还是负数 c++
Bit masking to determine if number is positive or negative c++
我想复制微控制器的行为。
如果程序计数器的内存位置包含0x26
那么我想检查下一个内存位置中的值是正数还是负数。
如果它是正数,那么我将其添加到程序计数器PC
如果它是负数,则将其添加到程序计数器PC
,这实际上是减去它。
我正在使用位掩码来执行此操作,但是在确定负值时遇到问题。
{
if (value_in_mem && 128 == 128)
{
cout << "nNext byte is : " << value_in_mem << endl;
cout << "nNumber is positive!" << endl;
PC = PC + value_in_mem;
cout << "n(Program Counter has been increased)" << endl;
}
else if (value_in_mem && 128 == 0)
{
cout << "nNext byte is : - " << value_in_mem << endl;
cout << "nNumber is negative!" << endl;
PC = PC + value_in_mem;
cout << "n(Program Counter has been decreased)" << endl;
}
}
我的方法是用 128 (0b10000000
)&&
value_in_mem
(一个 8 位有符号的 int),以确定最高有效位是 1 还是 0,负数还是后缀。
value_in_mem
是一个 8 位十六进制值,我认为这就是我的困惑所在。 我不完全确定负十六进制值是如何工作的,有人可以解释这一点以及我尝试代码时的错误吗?
1)你正在使用&&
,这是一个逻辑AND,但你应该使用&
,这是一个按位的AND。
// It would be better to use hex values when you're working with bits
if ( value_in_mem & 0x80 == 0x80 )
{
// it's negative
}
else
{
// it's positive
}
2)您可以简单地将您的值与0
进行比较(如果value_in_mem
声明为char
)
if ( value_in_mem < 0 )
{
// it's negative
}
else
{
// it's positive
}
确保你对你的值使用正确的类型(或者在重要的地方强制转换它们,例如,如果你更喜欢在大多数时候将内存值作为无符号字节(我当然会),然后仅将其转换为有符号 8 位整数,以便通过static_cast<int8_t>(value_in_mem)
进行特定的计算/比较)。
为了证明正确键入的重要性,以及编译器将如何为您完成所有繁琐C++工作,因此您不必为位而烦恼,也可以使用if (x < 0)
:
#include <iostream>
int main()
{
{
uint16_t pc = 65530; int8_t b = 0xFF; pc += b;
std::cout << pc << "n"; // unsigned 16 + signed 8
// 65529 (b works as -1, 65530 - 1 = 65529)
}
{
int16_t pc = 65530; int8_t b = 0xFF; pc += b;
std::cout << pc << "n"; // signed 16 + signed 8
// -7 (b works as -1, 65530 as int16_t is -6, -6 + -1 = -7)
}
{
int16_t pc = 65530; uint8_t b = 0xFF; pc += b;
std::cout << pc << "n"; // signed 16 + unsigned 8
// 249 (b works as +255, 65530 as int16_t is -6, -6 + 255 = 249)
}
{
uint16_t pc = 65530; uint8_t b = 0xFF; pc += b;
std::cout << pc << "n"; // unsigned 16 + unsigned 8
// 249 (b = +255, 65530 + 255 = 65785 (0x100F9), truncated to 16 bits = 249)
}
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组