Answers for "c# convert string to binary"

C#
1

c# convert binary string to integer

// How to generate a random binary number
public static int rndNumber = 0;
public static int answerInt = 0;
public static string fullStr = null;
public static string answerStr = null;

static void Main(string[] args)
{
    Console.Write("Random binary number: ");
    Random r = new Random();
  	// The 'ctr <= 3' part of the program means the binary number will
  	// have a length of 4. The for loop will loop until ctr == 4.
    for (int ctr = 0; ctr <= 3; ctr++)
    {
        // Generate either 0 or 1
        rndNumber = r.Next(0, 2);
        Console.Write(rndNumber);
        // Convert rndNumber int to string and append number to str
        string numStr = rndNumber.ToString();
        fullStr += numStr;
    }
    // Convert str to int and return answer
    answerInt = Convert.ToInt32(string.Format("{0}", fullStr));
    Console.WriteLine("nInt: " + answerInt);
    answerStr = answerInt.ToString("D4");
    Console.WriteLine("String: " + answerStr);
}

// OUTPUT:
Random binary number: 0010
Int: 10
String: 0010
Posted by: Guest on November-14-2021
1

c# to binary

int value = 8;
string binary = Convert.ToString(value, 2);
// binary to base 10
int value = Convert.ToInt32("1101", 2)
Posted by: Guest on May-30-2020
0

c# code to convert decimal to binary

int  n, i;       
       int[] a = new int[10];     
       Console.Write("Enter the number to convert: ");    
       n= int.Parse(Console.ReadLine());     
       for(i=0; n>0; i++)      
        {      
         a[i]=n%2;      
         n= n/2;    
        }      
       Console.Write("Binary of the given number= ");      
       for(i=i-1 ;i>=0 ;i--)      
       {      
        Console.Write(a[i]);      
       }
Posted by: Guest on May-10-2020
-1

c# string to binary

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
Posted by: Guest on September-19-2021

Code answers related to "c# convert string to binary"

C# Answers by Framework

Browse Popular Code Answers by Language