51

I need to convert int to bin and with extra bits.

string aaa = Convert.ToString(3, 2);

it returns 11, but I need 0011, or 00000011.

How is it done?

10 Answers 10

91

11 is binary representation of 3. The binary representation of this value is 2 bits.

3 = 20 * 1 + 21 * 1

You can use String.PadLeft(Int, Char) method to add these zeros.

// convert number 3 to binary string. 
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011
Sign up to request clarification or add additional context in comments.

1 Comment

what if the number is changing. like for example I am reading a file and converting the decimals in this file to binary (8bits each). In this case the number of zeros will be different from decimal to decimal.
3

You can use these methods:

public static class BinaryExt
{
    public static string ToBinary(this int number, int bitsLength = 32)
    {
        return NumberToBinary(number, bitsLength);
    }

    public static string NumberToBinary(int number, int bitsLength = 32)
    {
        string result = Convert.ToString(number, 2).PadLeft(bitsLength, '0');

        return result;
    }

    public static int FromBinaryToInt(this string binary)
    {   
        return BinaryToInt(binary);
    }

    public static int BinaryToInt(string binary)
    {   
        return Convert.ToInt32(binary, 2);
    }   
}

Sample:

int number = 3; 
string byte3 = number.ToBinary(8); // output: 00000011

string bits32 = BinaryExt.NumberToBinary(3); // output: 00000000000000000000000000000011

Comments

3

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....

Comments

3

For .NET 8 and above, use the Binary format specifier (B) with an explicit length value.

12345.ToString("B32");

// Output: 00000000000000000011000000111001

Bit mask example:

// Create an example mask with the lower 24 bits set to 1 and the upper 8 bits set to zero
int bits = 24;
int value= int.MaxValue >>> ((sizeof(int) * 8) - bits);

// Use a composite format string to render it to a zero-padded binary string
string paddedBinaryString= $"{value:B32}";

// Render to console
Console.WriteLine(paddedBinaryString);

// Output: 00000000011111111111111111111111

Comments

2

Since .NET 8+ you can do it simply by using the method ToString():

string s;
s = 42.ToString("b");        // .NET8+ => "101010".
s = Convert.ToString(42, 2); // .NET Framework 2+ to .NET7 => "101010".

s = 42.ToString("b16");                       // .NET8+ => "0000000000101010".
s = Convert.ToString(42, 2).PadLeft(16, '0'); // .NET Framework 2+ to .NET7 => "0000000000101010".

Source: Microsoft: Standard format specifiers .NET8+

Comments

1
public static String HexToBinString(this String value)
{
        String binaryString = Convert.ToString(Convert.ToInt32(value, 16), 2);
        Int32 zeroCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(binaryString.Length) / 8)) * 8;

        return binaryString.PadLeft(zeroCount, '0');
}

Comments

1

Just what Soner answered use:

Convert.ToString(3, 2).PadLeft(4, '0') 

Just want to add just for you to know. The int parameter is the total number of characters that your string and the char parameter is the character that will be added to fill the lacking space in your string. In your example, you want the output 0011 which which is 4 characters and needs 0's thus you use 4 as int param and '0' in char.

Comments

1

This may not be the most elegant solution but it is the fastest from my testing:

string IntToBinary(int value, int totalDigits) {
    char[] output = new char[totalDigits];
    int diff = sizeof(int) * 8 - totalDigits;
    for (int n = 0; n != totalDigits; ++n) {
        output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
    }
    return new string(output);
}
string LongToBinary(int value, int totalDigits) {
    char[] output = new char[totalDigits];
    int diff = sizeof(long) * 8 - totalDigits;
    for (int n = 0; n != totalDigits; ++n) {
        output[n] = (char)('0' + (char)((((ulong)value << (n + diff))) >> (sizeof(long) * 8 - 1)));
    }
    return new string(output);
}

This version completely avoids if statements and therfore branching which creates very fast and most importantly linear code. This beats the Convert.ToString() function from microsoft by up to 50%

Here is some benchmark code

long testConv(Func<int, int, string> fun, int value, int digits, long avg) {
    long result = 0;
    for (long n = 0; n < avg; n++) {
        var sw = Stopwatch.StartNew();
        fun(value, digits);
        result += sw.ElapsedTicks;
    }
    Console.WriteLine((string)fun(value, digits));
    return result / (avg / 100);//for bigger output values
}
string IntToBinary(int value, int totalDigits) {
    char[] output = new char[totalDigits];
    int diff = sizeof(int) * 8 - totalDigits;
    for (int n = 0; n != totalDigits; ++n) {
        output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
    }
    return new string(output);
}
string Microsoft(int value, int totalDigits) {
    return Convert.ToString(value, toBase: 2).PadLeft(totalDigits, '0');
}

int v = 123, it = 10000000;
Console.WriteLine(testConv(Microsoft, v, 10, it));
Console.WriteLine(testConv(IntToBinary, v, 10, it));

Here are my results

0001111011
122
0001111011
75

Microsofts Method takes 1.22 ticks while mine only takes 0.75 ticks

Comments

0
string aaa = Convert.ToString(3, 2).PadLeft(10, '0');

2 Comments

Got flagged for length+content - presumably because there is no explanation.
This was the first post with the answer. This answer is self-explanatory in my opinion.
0

With this you can get binary representation of string with corresponding leading zeros.

string binaryString = Convert.ToString(3, 2);;
int myOffset = 4;
string modified = binaryString.PadLeft(binaryString.Length % myOffset == 0 ? binaryString.Length : binaryString.Length + (myOffset - binaryString.Length % myOffset), '0'));

In your case modified string will be 0011, if you want you can change offset to 8, for instance, and you will get 00000011 and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.