This post is a continue from the previous post Integer to Binary Conversion Part 1.

Enhancement and Fix:
- Adding a menu system
- Overflow check
The code in C# :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | using System; class Program { static void Main(string[] args) { int num = 0, temp = 0, i = 0, menu = 0; int[] result = new int[8]; printMenu(); menu = readInt(); while(menu != 0){ Console.WriteLine("Enter an integer to convert to binary:"); num = readInt(); if (num > 255) { Console.WriteLine("The integer exceeds the limit of 8 bits binary"); }else { Console.WriteLine("Converting..... The result is:"); while (num != 0) { temp = num % 2; result[i] = temp; num /= 2; i++; } printResult(i, result); } i = 0; printMenu(); menu = readInt(); } } public static int readInt(){ return int.Parse(Console.ReadLine()); } public static void printMenu() { Console.WriteLine("============ INTEGER TO BINARY CONVERTER ============="); Console.WriteLine("1. Press any number to convert Integer to 8 bits binary"); Console.WriteLine("2. Press 0 to exit"); Console.WriteLine("======================================================="); Console.WriteLine(); } public static void printResult(int i, int []array) { Console.WriteLine("The 8 bits binary is: "); for(int k = (i - 1); k >= 0; k--){ Console.Write(array[k]); } Console.WriteLine(); Console.WriteLine(); } } |
I will try to improve the code snippet when I have the time again…

















