用位读取和写入负数

问题描述

因此,使用下面的代码,我可以将一个数字(例如2047)保存到一个使用位中,然后读回它,它将显示2047。如果我想对负数执行此操作(例如,如何执行此操作) -2048)

string text = "";
int cnt = 11;
List<int> bits = new List<int>();
for (int i = 11; i >= 0; i--)
{
    int t = (-2048 >> i) & 1;
    bits.Add(t);
}
int value=0;
for(int i=0;i<bits.Count;i++)
{
    text += bits[i];
    value &= ~(1 << cnt);

    if (bits[i] == 1)
    {
        value |= 1 << cnt;
    }
    else
    {
        value |= 0 << cnt;
    }

    cnt--;
}
MessageBox.Show(value+ " " +text);

我想使用的数字范围是-2048到2047

解决方法

经过一段时间的思考,我已经弄清楚了。只需在输出之前添加以下代码

if(value> 2047)
{
    value -= 4096; 
}

然后-2048实际上将显示-2048而不是2048