I'm creating a lottery program that users can choose from a series of numbers between a particular range and the program then creates its own version of numbers and compares those user values against the program's random numbers which any matches that the program then finds are then displayed to the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assessment1.Lottery
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert 6 lottery numbers:");
int range = 100;
int minValue = 0;
int maxValue = 100;
int a = 0;
Random rnd = new Random();
int[] myArray = new int[6];
for ( int i=0; i < myArray.Length; i++ )
{
int randomNumber = rnd.Next(minValue, maxValue);
myArray[i] = randomNumber;
Console.WriteLine(randomNumber);
myArray[i] = int.Parse(Console.ReadLine());
Console.WriteLine(myArray[i]);
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out myArray[a]))
a++;
else
Console.WriteLine("invalid integer");
}
double arry = myArray.Average();
if(arry > 0)
Console.WriteLine("found");
else
Console.WriteLine("not found");
int BinarySearch(int[] array, int value, int low, int high)
{
if ( high >= low)
{
int mid = (low + high) / 2;
if (array[mid] == value) return mid;
if (array[mid] == value) return BinarySearch(array, value, low, mid - 1);
return BinarySearch(array, value, mid + 1, high);
}
return -1;
}
}
Console.ReadLine();
}
}
}
when I run the program it shows the following
Please insert 6 lottery numbers: 64
how can I fix this so that the array can be filled with user input
Here is a version of something I wrote a while back and modified to your parameters, if there are bugs please don't ask me to fix.
static void Main(string[] args)
{
int stop = 0;
int[] chosenNum = new int[6];
while (stop == 0)
{
Console.Clear();
string con = "";
Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
string numbers = Console.ReadLine();
string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
if (userNumbers.Count() < 6)
{
Console.WriteLine("You entered less than six numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (userNumbers.Count() > 6)
{
Console.WriteLine("You entered more than 6 numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (checkDup.Count() < 6)
{
Console.WriteLine("You entered duplicate numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (!isNumeric(userNumbers))
{
Console.WriteLine("You entered non-numeric value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (isInRange(userNumbers) < 6)
{
Console.WriteLine("You entered out of range value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else
{
var lowerBound = 1;
var upperBound = 100;
var random = new Random();
int[] randomNum = new int[6];
int count = 0;
foreach(string str in userNumbers){
var rNum = random.Next(lowerBound, upperBound);
randomNum[count] = rNum;
count++;
}
string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
Array.Sort(userNumbers);
Array.Sort(ourPicks);
//string[] ourpicks = { "1", "2" };//for testing
Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
string[] result = userNumbers.Intersect(ourPicks).ToArray();
if(result.Count() > 0)
{
Console.WriteLine("Matchs: {0}", string.Join(", ", result));
}
else
{
Console.WriteLine("Match's = 0");
}
stop = 1;
}
}
Console.ReadLine();
}
public static bool isNumeric(string[] num)
{
foreach (string str in num)
{
bool check = int.TryParse(str, out int test);
if (!check)
{
return false;
}
}
return true;
}
public static int isInRange(string[] num)
{
int count = 0;
foreach (string str in num)
{
int.TryParse(str, out int test);
if (test > 0 & test <= 100)
{
count++;
}
}
return count;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need some help with this program I got from a programming website, I am still new to programming and this seems like too much for me right now. I don't even know where to begin with this program:
In one of the last problems, you created the most recent version of the GreenvilleRevenue program, which prompts the user for contestant data for this year’s Greenville Idol competition. Now, save all the entered data to a Greenville.ser file(this is provided by the website) that is closed when data entry is complete and then reopened and read in, allowing the user to view lists of contestants with requested talent types. The program should output the name of the contestant, the talent, and the fee.
using System;
using static System.Console;
class GreenvilleRevenue
{
static void Main()
{
const int MIN_CONTESTANTS = 0;
const int MAX_CONTESTANTS = 30;
int num;
int revenue = 0;
const char QUIT = 'Z';
char option = ' ';;
Contestant[] contestants = new Contestant[MAX_CONTESTANTS];
num = getContestantNumber(MIN_CONTESTANTS, MAX_CONTESTANTS);
revenue = getContestantData(num, contestants, revenue);
WriteLine("\n\nRevenue expected this year is {0}", revenue.ToString("C"));
while(option != QUIT)
option = getLists(num, contestants);
}
private static int getContestantNumber(int min, int max)
{
string entryString;
int num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
while(num < min || num > max)
{
if(!int.TryParse(entryString, out num))
{
WriteLine("Format invalid");
num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
}
else
{
try
{
if(num < min || num > max)
throw(new ArgumentException());
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("Number must be between {0} and {1}", min, max);
num = max + 1;
Write("Enter number of contestants >> ");
entryString = ReadLine();
}
}
}
return num;
}
private static int getContestantData(int num, Contestant[] contestants, int revenue)
{
const int ADULTAGE = 17;
const int TEENAGE = 12;
int x = 0;
string name;
char talent;
int age;
int pos;
while(x < num)
{
Write("Enter contestant name >> ");
name = ReadLine();
WriteLine("Talent codes are:");
for(int y = 0; y < Contestant.talentCodes.Length; ++y)
WriteLine(" {0} {1}", Contestant.talentCodes[y], Contestant.talentStrings[y]);
Write(" Enter talent code >> ");
char.TryParse(ReadLine(), out talent);
try
{
validateCode(talent, out pos);
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("{0} is not a valid code. Assigned as Invalid.", talent);
}
Write(" Enter contestant's age >> ");
int.TryParse(ReadLine(), out age);
if(age > ADULTAGE)
contestants[x] = new AdultContestant();
else
if(age > TEENAGE)
contestants[x] = new TeenContestant();
else
contestants[x] = new ChildContestant();
contestants[x].Name = name;
contestants[x].TalentCode = talent;
revenue += contestants[x].Fee;
++x;
}
return revenue;
}
private static char getLists(int num, Contestant[] contestants)
{
int x;
char QUIT = 'Z';
char option = ' ';
bool isValid;
int pos = 0;
bool found;
WriteLine("\nThe types of talent are:");
for(x = 0; x < Contestant.talentStrings.Length; ++x)
WriteLine("{0, -6}{1, -20}", Contestant.talentCodes[x], Contestant.talentStrings[x]);
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
isValid = false;
while(!isValid)
{
if(!char.TryParse(ReadLine(), out option))
{
isValid = false;
WriteLine("Invalid format - entry must be a single character");
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
}
else
{
if(option == QUIT)
isValid = true;
else
{
try
{
validateCode(option, out pos);
isValid = true;
}
catch(ArgumentException e)
{
WriteLine(e.Message);
WriteLine("{0} is not a valid code", option);
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
isValid = false;
}
}
if(isValid && option != QUIT)
{
WriteLine("\nContestants with talent {0} are:", Contestant.talentStrings[pos]);
found = false;
for(x = 0; x < num; ++x)
{
if(contestants[x].TalentCode == option)
{
WriteLine(contestants[x].ToString());
found = true;
}
}
if(!found)
{
WriteLine("No contestants had talent {0}", Contestant.talentStrings[pos]);
isValid = false;
Write("\nEnter a talent type or {0} to quit >> ", QUIT);
}
}
}
}
return option;
}
public static void validateCode(char option, out int pos)
{
bool isValid = false;
pos = Contestant.talentCodes.Length - 1;
for(int z = 0; z < Contestant.talentCodes.Length; ++z)
{
if(option == Contestant.talentCodes[z])
{
isValid = true;
pos = z;
}
}
if(!isValid)
throw(new ArgumentException());
}
}
class Contestant
{
public static char[] talentCodes = {'S', 'D', 'M', 'O'};
public static string[] talentStrings = {"Singing", "Dancing",
"Musical instrument", "Other"};
public string Name {get; set;}
private char talentCode;
private string talent;
private int fee;
public char TalentCode
{
get
{
return talentCode;
}
set
{
int pos = talentCodes.Length;
for(int x = 0; x < talentCodes.Length; ++x)
if(value == talentCodes[x])
pos = x;
if(pos == talentCodes.Length)
{
talentCode = 'I';
talent = "Invalid";
}
else
{
talentCode = value;
talent = talentStrings[pos];
}
}
}
public string Talent
{
get
{
return talent;
}
}
public int Fee
{
get
{
return fee;
}
set
{
fee = value;
}
}
}
class AdultContestant : Contestant
{
public int ADULT_FEE = 30;
public AdultContestant()
{
Fee = ADULT_FEE;
}
public override string ToString()
{
return("Adult Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
class TeenContestant : Contestant
{
public int TEEN_FEE = 20;
public TeenContestant()
{
Fee = TEEN_FEE;
}
public override string ToString()
{
return("Teen Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
class ChildContestant : Contestant
{
public int CHILD_FEE = 15;
public ChildContestant()
{
Fee = CHILD_FEE;
}
public override string ToString()
{
return("Child Contestant " + Name + " " + TalentCode + " Fee " + Fee.ToString("C"));
}
}
I agree with Mark's opinion, as well as the others who have up-voted his comment.
I wouldn't wait on someone to post a solution to your question so I'll go ahead and give you some things to get started on your own research and solution.
(Most of this is already in your problem statement, just broken down)
Start with the existing code you've pasted in
Read it line by line and google/textbook/stackoverflow ANYTHING you don't understand. Get a general understanding, and go deep if you have time.
Learn how to save data to a file in C#
Learn how to load data from a file in C#
Find a place in the code for the save data logic. (after data entry)
Run load data logic after save data logic
Display what was loaded
Edit: As you do research, you'll find lots of stackoverflow posts with good answers. Follow the format for those questions (prior research, attempted solutions, specific question, small code snippets) in order to ask more engaging questions yourself.
I have to create a program that breaks after the sum of the digits of a number is bigger than 20.(The code seems to break after one entry(i entered the number 5))This is my attempt:
class Program
{
static void Main(string[] args)
{
int sum = 0;
while (sum < 20)
{
string number = Console.In.ReadLine();
foreach (int num in number)
{
sum += num;
}
if (sum >= 20)
{
break;
}
sum = 0;
}
}
}
Your code makes no sense however the issue is the ascii value instead of int indicated below:
string numero = Console.In.ReadLine();
foreach (int num in numero) ----> This takes ascii value of the char NOT int value
Try this code out:
public static int CharToInt(char input)
{
int result = -1;
if (input >= 48 && input <= 57)
{
result = input - '0';
}
return result;
}
static void Main(string[] args)
{
int soma = 0;
while (soma < 20)
{
Console.WriteLine("Soma is:" + soma);
string numero = Console.In.ReadLine();
foreach (char num in numero)
{
int value = CharToInt(num);
soma += value;
}
}
Console.WriteLine("Final Soma is:" + soma);
}
You have to convert the string number to an integer first with Int.TryParse().
I'd go this way:
class Program
{
static void Main(string[] args)
{
int sum = 0;
string number = Console.In.ReadLine();
foreach (var num in number.Select(digit => int.Parse(digit.ToString())))
{
sum += num;
if (sum >= 20)
break;
}
Console.WriteLine("Sum :{0}",sum);
Console.ReadLine();
}
}
this is Students.cs
It is showing an error "NullReferenceException was unhandled" at line ---- Console.WriteLine("Student{0}: {1}, {2:P} {3}", i+1, stuList[i].studentName,stuList[i].studentPercentage, stuList[i].studentLetterGrade);
Can I get help finding the error with this two classes
private static int studentCount = 0;
// Instance variables go here
private string studentName;
private double studentPercentage;
private string studentLetterGrade;
private Grade test = new Grade(0);
private Grade hwQz = new Grade(700);
//Default Constructor Method
public Student()
{
}//end of Student Constructor method
public Student(string name)
{
//if(name.Length == 0)
SetStudentName("Jane Doe");
//else
//SetStudentName(name);
}//end of Overloaded Constructor method
public Student(string name, int percent, string letter)
{
SetStudentName(name);
SetStudentPercent(percent);
SetStudentLetter(letter);
}//end of Overloaded Constructor method
//Class Methods
// retrieve the student count
public static int GetStudentCount()
{
return studentCount;
}//end of GetStudentCount method
// set the student count
public static void SetStudentCount(int newStudentCount)
{
studentCount = newStudentCount;
}//end of SetStudentCount method
// list students
public static void ListStudents(Student[] stuList)
{
//Clear Screen
Console.Clear();
for (int i = 0; i < studentCount; i++)
{
Console.WriteLine("Student{0}: {1}, {2:P} {3}", i+1, stuList[i].studentName,stuList[i].studentPercentage, stuList[i].studentLetterGrade);
}
}
// Instance methods go here
// retrieve the Student name
public string GetStudentName()
{
return studentName;
}//end of GetStudentName method
// set the Student name
public void SetStudentName(string newName)
{
studentName = newName;
}//end of SetStudentName method
// retrieve the Student percent
public double GetStudentPercent()
{
return studentPercentage;
}//end of GetStudentPercent method
// set the Student address
public void SetStudentPercent(double newPercent)
{
studentPercentage = newPercent;
}//end of SetStudentPercent method
// retrieve the Student Letter
public string GetStudentLetter()
{
return studentLetterGrade;
}//end of GetStudentLetter method
// set the Student letter
public void SetStudentLetter(string newLetter)
{
studentLetterGrade = "A+";
}//end of SetStudentLetter method
public void EnterStudentScores()
{
test.EnterScores("Test");
hwQz.EnterScores("Homework & Quiz");
//Store the overall score in a temp variable
double gradePercent = ((50 * test.GetGradePercent()) + (50 * hwQz.GetGradePercent()));
//Using typecasting to force a double into an int data type
SetStudentPercent(gradePercent);
SetStudentLetter(test.GetLetterGrade(gradePercent));
}
}
}
The above Students.cs is connected with Menu.cs
bool runApp = true;
Student[] students = new Student[35];
//Application loop
while (runApp)
{
Console.Clear();
Console.WriteLine("\n\tGrade Book Menu\n");
Console.WriteLine("\t1) Add Student");
Console.WriteLine("\t2) Enter Student Grades");
Console.WriteLine("\t3) List Student Grades");
Console.Write("\nEnter Selection or Press Escape to exit: ");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
runApp = false;
}
else
{
switch (key.Key)
{
case ConsoleKey.NumPad1:
case ConsoleKey.D1:
//Get the current student count stored in the Student Class variable
int indexForNewStudent = Student.GetStudentCount();
indexForNewStudent = 0;
Console.Write("\nEnter Student Name: ");
//Instantiate a Student object and place it in the array of Student objects called student
students[indexForNewStudent] = new Student(Console.ReadLine()); //Call overloaded constructor
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
break;
case ConsoleKey.NumPad2:
case ConsoleKey.D2:
Console.WriteLine("\nEnter the Student Number. Use List Students to get Student Number.");
int studentNumber = 0; //Temporary variable to hold the student number to enter grades
//Test the entered string is a number and between 1 and 30
if ((int.TryParse(Console.ReadLine(), out studentNumber)) && (studentNumber >= 1) &&
(studentNumber <= 30))
{
//In the event a student has not been added this code will crash
if (Student.GetStudentCount() > 0) //Has a student been added?
students[studentNumber - 1].EnterStudentScores(); //Subtract 1 from enterd number for array index
else
Console.WriteLine("A student has not been added");
}
else
{
Console.WriteLine("Invalid Student Number. Enter a number from 1 to 30");
}
break;
case ConsoleKey.NumPad3:
case ConsoleKey.D3:
Student.ListStudents(students);
break;
default:
Console.WriteLine("Invalid Menu Selection");
break;
}
Console.Write("Press a key to return to Menu");
Console.ReadKey();
}
}
Console.Write("\nExiting Application. Press any key to close window... ");
Console.ReadKey();
}
}
}
This code is also connect with the following Grade.cs
private double[] earnedScores = new double[30];
private double pointTotal = 0;
private int scoresEntered = 0;
public Grade()
{
}
public Grade(double total)
{
pointTotal = total;
}
public void SetPointTotal(int total)
{
pointTotal = (double)total; //using double to type cast an int into a double
}
public void SetPointTotal(double total) // Overloaded method for SetPointTotal
{
pointTotal = total;
}
public void EnterScores(string scoreType)
{
//Loop that lets the user enter up to 30 scores
//the loop ends after 30 entries or Q is pressed
do
{
Console.Clear(); //Clear screen
//scoreType is a string passed in that prints to the screen to help user know what scores are being entered
Console.WriteLine("{0} Scores", scoreType);
Console.WriteLine("Enter up to {0} scores or Q to quit.", earnedScores.Length);
Console.Write("Enter score{0}: ", scoresEntered + 1);
string input = Console.ReadLine();
//Validate user entered string stored in input.
//Return -2 if Q was pressed and -1 if the string is invalid
double inputNumber = ValidateScore(input);
if (inputNumber == -1)
{
Console.WriteLine("Invalid entry. Please enter a valid positive score.");
Console.ReadKey();
}
else if (inputNumber == -2)
{
break;
}
else
{
earnedScores[scoresEntered] = inputNumber;
scoresEntered++;
}
} while(scoresEntered < earnedScores.Length);
}
public void DisplayScore(string scoreType)
{
//scoreType is a string passed in that prints to the screen to help user know what scores are being displayed
Console.WriteLine("{0} Scores", scoreType);
//Loop thru the earnedScores array and print each element's value
for (int i = 0; i < scoresEntered; i++)
{
Console.WriteLine("Score{0}: {1}", i + 1, earnedScores[i]);
}
}
public double ValidateScore(string inText)
{
int dotCount = 0; //Variable to hold the count of decimals
char[] temp = inText.ToCharArray(); //char array to hold incoming string
if (inText.Length > 0) //text is not blank if length greater than zero
{
for (int i = 0; i < inText.Length; i++) //loop thru each character and test contents
{
if (temp[i] == '.') //is it a decimal
{
dotCount += 1; //dotCount++; does the same thing
if (dotCount > 1) //More than 1 decimal invalid
return -1;
}
else if (temp[i] == '-') //if Negative sign
{
if (i != 0) //If Negative is not 1st element of array then invalid
return -1;
}
else if (!char.IsNumber(temp[i])) //If character is not a number
{
if (temp[i] == 'Q' || temp[i] == 'q') //If Q or q then exit loop
{
return -2;
}
else //Any other letter invalid
{
return -1;
}
}
}
}
else
{
return -1; //Blank was entered
}
return Convert.ToDouble(inText);
}
public double GetGradePercent()
{
double totalEarnedPoints = 0; //Start with zero
//Add all elements of the array to total
for (int i = 0; i < scoresEntered; i++)
{
totalEarnedPoints += earnedScores[i];
}
//Return grade percentage by dividing earned points by total points
return totalEarnedPoints / pointTotal;
}
public string GetLetterGrade(double percentage)
{
//Incoming parameter will be in decimal format. Example 90% will be 0.90
percentage *= 100; //Multiply incoming percentage by 100 to move decimal point scaling number from 0 to 100
if (percentage >= 97.0)
{
return "A+";
}
else if ((percentage < 97) && (percentage >= 93))
{
return "A";
}
else if ((percentage < 93) && (percentage >= 90))
{
return "A-";
}
else if ((percentage < 90) && (percentage >= 87))
{
return "B+";
}
else if ((percentage < 87) && (percentage >= 83))
{
return "B";
}
else if ((percentage < 83) && (percentage >= 80))
{
return "B-";
}
else if ((percentage < 80) && (percentage >= 77))
{
return "C+";
}
else if ((percentage < 77) && (percentage >= 70))
{
return "C";
}
else if ((percentage < 70) && (percentage >= 60))
{
return "D";
}
else
{
return "E";
}
}
public void ClearScores()
{
scoresEntered = 0; //Clear number of scores previously entered
//Reset all elements of the array back to zero
for (int i = 0; i < earnedScores.Length; i++)
{
earnedScores[i] = 0.0;
}
}
}
}
In your add student code you have a couple of problems
indexForNewStudent = 0;
This means you will always be overwriting the first student rather than adding a new one.
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
The +2 here means that your student count will be 1 greater than the number of students, meaning that the ListStudents function will then try to access a student that hasn't been added yet. It should be +1
How to convert an integer number into its binary representation?
I'm using this code:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
But it throws an exception:
Could not find any parsable digits
Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.
int value = 8;
string binary = Convert.ToString(value, 2);
Which returns 1000.
Convert from any classic base to any base in C#
string number = "100";
int fromBase = 16;
int toBase = 10;
string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
Supported bases are 2, 8, 10 and 16
Very Simple with no extra code, just input, conversion and output.
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
primitive way:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n / 2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
Another alternative but also inline solution using Enumerable and LINQ is:
int number = 25;
string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.
So you're getting an error because "8" is not a valid digit in base 2.
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
Will show 15 (1111 base 2 = 15 base 10)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
Will show 61440.
static void convertToBinary(int n)
{
Stack<int> stack = new Stack<int>();
stack.Push(n);
// step 1 : Push the element on the stack
while (n > 1)
{
n = n / 2;
stack.Push(n);
}
// step 2 : Pop the element and print the value
foreach(var val in stack)
{
Console.Write(val % 2);
}
}
I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.
public static string ByteConvert (int num)
{
int[] p = new int[8];
string pa = "";
for (int ii = 0; ii<= 7;ii = ii +1)
{
p[7-ii] = num%2;
num = num/2;
}
for (int ii = 0;ii <= 7; ii = ii + 1)
{
pa += p[ii].ToString();
}
return pa;
}
using System;
class Program
{
static void Main(string[] args) {
try {
int i = (int) Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));
} catch(Exception e) {
Console.WriteLine("\n{0}\n", e.Message);
}
}
public static string ToBinary(Int64 Decimal) {
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0) {
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}
This function will convert integer to binary in C#:
public static string ToBinary(int N)
{
int d = N;
int q = -1;
int r = -1;
string binNumber = string.Empty;
while (q != 1)
{
r = d % 2;
q = d / 2;
d = q;
binNumber = r.ToString() + binNumber;
}
binNumber = q.ToString() + binNumber;
return binNumber;
}
class Program
{
static void Main(string[] args)
{
var #decimal = 42;
var binaryVal = ToBinary(#decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 6;
binaryVal = ToBinary(#decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 47;
binaryVal = ToBinary(#decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 99;
binaryVal = ToBinary(#decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
#decimal = 16;
binaryVal = ToBinary(#decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
Console.WriteLine();
#decimal = 11;
binaryVal = Convert.ToString(#decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int #base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % #base;
reverseBinary += remainder;
round = (int)(number / #base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int #base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var #char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(#base, pow) * #char;
}
return val;
}
}
Learning sources:
Everything you need to know about binary
including algorithm to convert decimal to binary
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
BCL provided Convert.ToString(n, 2) is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.
Following custom implementation works for all integers(-ve and +ve).
Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
Above code is my implementation. So, I'm eager to hear any feedback :)
// I use this function
public static string ToBinary(long number)
{
string digit = Convert.ToString(number % 2);
if (number >= 2)
{
long remaining = number / 2;
string remainingString = ToBinary(remaining);
return remainingString + digit;
}
return digit;
}
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}
This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10) returns the string "1010".
I came across this problem in a coding challenge where you have to convert 32 digit decimal to binary and find the possible combination of the substring.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
int numberofinputs = int.Parse(Console.ReadLine());
List<BigInteger> inputdecimal = new List<BigInteger>();
List<string> outputBinary = new List<string>();
for (int i = 0; i < numberofinputs; i++)
{
inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
}
//processing begins
foreach (var n in inputdecimal)
{
string binary = (binaryconveter(n));
subString(binary, binary.Length);
}
foreach (var item in outputBinary)
{
Console.WriteLine(item);
}
string binaryconveter(BigInteger n)
{
int i;
StringBuilder output = new StringBuilder();
for (i = 0; n > 0; i++)
{
output = output.Append(n % 2);
n = n / 2;
}
return output.ToString();
}
void subString(string str, int n)
{
int zeroodds = 0;
int oneodds = 0;
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
string substring = "";
for (int k = i; k <= j; k++)
{
substring = String.Concat(substring, str[k]);
}
var resultofstringanalysis = stringanalysis(substring);
if (resultofstringanalysis.Equals("both are odd"))
{
++zeroodds;
++oneodds;
}
else if (resultofstringanalysis.Equals("zeroes are odd"))
{
++zeroodds;
}
else if (resultofstringanalysis.Equals("ones are odd"))
{
++oneodds;
}
}
}
string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
outputBinary.Add(outputtest);
}
string stringanalysis(string str)
{
int n = str.Length;
int nofZeros = 0;
int nofOnes = 0;
for (int i = 0; i < n; i++)
{
if (str[i] == '0')
{
++nofZeros;
}
if (str[i] == '1')
{
++nofOnes;
}
}
if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
{
return "both are odd";
}
else if (nofZeros != 0 && nofZeros % 2 != 0)
{
return "zeroes are odd";
}
else if (nofOnes != 0 && nofOnes % 2 != 0)
{
return "ones are odd";
}
else
{
return "nothing";
}
}
Console.ReadKey();
}
}
}
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
This was a interesting read i was looking for a quick copy paste.
I knew i had done this before long ago with bitmath differently.
Here was my take on it.
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
You could stick spacing in there with a bit of modulos in the loop.
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;
var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
Just one line for 8 bit
Console.WriteLine(Convert.ToString(n, 2).PadLeft(8, '0'));
where n is the number