C# Convert negative int to 11 bits
- by Klemenko
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?