I need to convert int to bin and with extra bits.
string aaa = Convert.ToString(3, 2);
it returns 11
, but I need 0011
I've created a method to dynamically write leading zeroes
public static string ToBinary(int myValue)
{
string binVal = Convert.ToString(myValue, 2);
int bits = 0;
int bitblock = 4;
for (int i = 0; i < binVal.Length; i = i + bitblock)
{ bits += bitblock; }
return binVal.PadLeft(bits, '0');
}
At first we convert my value to binary. Initializing the bits to set the length for binary output. One Bitblock has 4 Digits. In for-loop we check the length of our converted binary value und adds the "bits" for the length for binary output.
Examples: Input: 1 -> 0001; Input: 127 -> 01111111 etc....