位掩码以确定数字是正数还是负数c ++

时间:2017-03-03 09:50:14

标签: 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;
                }
            }

我的方法是&& value_in_mem(一个8位带符号的int)和128(0b10000000)来确定最高有效位是1还是0,负数还是后置

value_in_mem是一个8位十六进制值,我认为这就是我的困惑所在。我不完全确定负十六进制值是如何工作的,有人可能会解释这个以及我在代码中尝试的错误吗?

2 个答案:

答案 0 :(得分:0)

1)您使用的&&logical AND,但您应该使用& bitwise 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
}

答案 1 :(得分:0)

确保为值使用正确的类型(或者将它们转换到重要的位置,如果您更喜欢在大多数情况下将内存值作为无符号字节(我当然会),然后将其转换为带符号的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)
    }
}