C# Convert negative int to 11 bits

Posted by Klemenko on Stack Overflow See other posts from Stack Overflow or by Klemenko
Published on 2013-10-25T09:51:50Z Indexed on 2013/10/25 9:53 UTC
Read the original article Hit count: 212

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about binary