Question

I need to convert numbers in interval [–1024, 1016]. I'm converting to 11 bits like that:

string s = Convert.ToString(value, 2); //Convert to binary in a string

int[] bits = s.PadLeft(11, '0') // Add 0's from left
                     .Select(c => int.Parse(c.ToString())) // convert each char to int
                     .ToArray(); // Convert IEnumerable from select to Array

This works perfectly for signed integers [0, 1016]. But for negative integers I get 32 bits result. Do you have any idea how to convert negative integers to 11 bits array?

Was it helpful?

Solution

If you only care about the first 11 bits, then just apply a mask:

string s = Convert.ToString(value & 2047, 2);

This will restrict the value to at most 11 bits - and for negative numbers, all the "unused" bits will be 1s.

For reference: 2047 is binary 0000 ... 0000 0111 1111 1111, i.e. a mask of the least significant 11 bits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top