Read and write negative numbers with bits

So with the code below i can save a number (for example 2047) into an using bits and then read it back and it will display 2047. How do i do this if i want to do this for negative numbers (for example -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);

Also the range of numbers i want this to work with is -2048 to 2047



from Recent Questions - Stack Overflow https://ift.tt/37KMbjl
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation