How to add chars numerically in c# - c#

So I'm building a program that takes a string and turns it into a binary number (I.E. "A" = 01000001). Then, if the user wishes, it can that binary number convert it back into a ascii character. Here the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace NDR_011
{
class Program
{
public static Byte[] BinStr(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return list.ToArray();
}
public static void Print(object mess)
{
string tmp = mess.ToString().ToUpper();
Console.Write(tmp);
}
private static List<string> buffer = new List<string>();
private static string outfile = "C:/tmp/bytes.bin";
static void Main(string[] args)
{
string tmp = "";
Print("NDR 011\n");
while (true)
{
Print(""); tmp = Console.ReadKey().Key.ToString().ToUpper();
if (Console.CursorLeft > 0)
{
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
if (tmp == ConsoleKey.F1.ToString())
{
break;
} else if (tmp == ConsoleKey.F2.ToString())
{
comp();
continue;
} else if (tmp == ConsoleKey.F4.ToString())
{
buffer.Clear();
continue;
} else if (tmp == ConsoleKey.F5.ToString())
{
Print("N "); string a = Console.ReadLine();
outfile = a;
continue;
} else if (tmp == ConsoleKey.F5.ToString())
{
outfile = "C:/tmp/bytes.bin";
Print("Out file reset\n");
continue;
} else if (tmp == ConsoleKey.F7.ToString())
{
//Print("N "); // string a = Console.ReadLine();
string a = "C:/tmp/bytes.bin";
string[] s = File.ReadAllText(a).Split(' ');
char[] end = new char[s.Length - 1];
for (int i=0;i<end.Length;i++)
{
end[i] = (char)BinStr(s[i])[0];
//Print(end[i]);
}
//Print((char)BinStr(s[0])[0]);
if (end[0] == 'A' && end[1] == 'D' && end[2] == 'D')
{
for (int i=0+3;i<end.Length;i++)
{
int n = end[i] + end[i];
Print(n);
}
}
//decompile(a);
continue;
}
while (tmp.Length > 1)
{
char a = tmp[tmp.Length - 1];
tmp = a.ToString();
}
buffer.Add(tmp);
}
}
static void comp()
{
if (buffer == null || buffer.Count <= 0)
{
Print("Error buffer empty");
return;
}
char[] r = new char[buffer.Count];
for (int i=0;i<buffer.Count;i++)
{
r[i] = Convert.ToChar(buffer[i]);
Print(r[i]);
}
foreach (char ch in r)
{
string a = Convert.ToString((int)ch, 2);
while (a.Length != 8)
{
string b = "0";
a = b + a;
}
File.AppendAllText(outfile, a + " ");
}
Print("Compile done!\n");
}
static void decompile(string filename)
{
}
static void run()
{
}
}
}
(the indenation got messed up when I add to this post.)
The problem is this: when I try to add the values I get from the file I get random numbers like: 100102, and odd stuff like that. What am I doing wrong? Thanks

Here's how you convert a string to a binary string of 1s and 0s:
var binstring = string.Join(" ", Encoding.ASCII.GetBytes(("Welcome, World!")).Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
To convert that back into a string, we will need to a parse byte[] array from it with a method like so:
public static byte[] GetBytes(string s)
{
byte[] result = new byte[(s.Length + 7) / 8];
int i = 0;
int j = 0;
foreach (char c in s)
{
result[i] <<= 1;
if (c == '1')
result[i] |= 1;
j++;
if (j == 8)
{
i++;
j = 0;
}
}
return result;
}
Then we get those bytes and we can simply convert it into a string using:
Encoding.ASCII.GetString(GetBytes(binstring));
References: How could I encode a string of 1s and 0s for transport?How to get the binary code behind ASCII (C#)

Related

C# RNGCryptoServiceProvider and special characters

I'm looking for a way to get random characters.I need a string must be contain at 2 least uppercase letters, at least 1 number and special characters.
Here is my code:
public static string CreateRandomPassword(int Length)
{
string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
Byte[] randomBytes = new Byte[Length];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
var chars = new char[Length];
int Count = _Chars.Length;
for(int i = 0;i<Length;i++)
{
chars[i] = _Chars[(int)randomBytes[i] % Count];
}
return new string(chars);
}
some results:
ZNQzvUPFKOL3x
BQSEkKHXACGO
They haven't special characters and numbers.
your code works great! I've just wrapped it with a function that validate your conditions.
I've executed the following:
public static string CreateRandomPassword(int Length)
{
string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
Byte[] randomBytes = new Byte[Length];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
var chars = new char[Length];
int Count = _Chars.Length;
for (int i = 0; i < Length; i++)
{
chars[i] = _Chars[(int)randomBytes[i] % Count];
}
return new string(chars);
}
public static string CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(int length)
{
while (true)
{
var pass = CreateRandomPassword(length);
int upper=0, num =0, special = 0,lower=0;
foreach (var c in pass)
{
if (c > 'A' && c < 'Z')
{
upper++;
}
else if (c > 'a' && c < 'z')
{
lower++;
}
else if (c > '0' && c < '9')
{
num++;
}
else
{
special++;
}
}
if (upper>=2&&num>=1&&1>=special)
{
return pass;
}
}
}
[Test]
public void CreateRandomPassword_Length13_RandomPasswordWithNumbers()
{
var random = CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(13);
Assert.IsTrue(true);
}

Splitting String N into 4 distinct strings

The string has to be split into 4 pairwise different non-empty parts. For example,
"happynewyear" could become ["happy", "new", "ye" and "ar"]
No deletion, change of order of characters is permitted.
This question was part of an online competition, which is now over. I have written the following C# code which works for the test cases which I have run but it failed in 3 test cases after submission. I am not sure what cases I might be missing, can anyone help?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hackerearth___India_Hacks
{
class Program
{
static void Main(string[] args)
{
var line1 = System.Console.ReadLine().Trim();
var N = Int32.Parse(line1);
string[] s = new string[N];
string result = "";
for (var i = 0; i < N; i++)
{
s[i] = System.Console.ReadLine().Trim();
result = result + "\n" + check(s[i]);
}
System.Console.Write(result);
Console.ReadKey();
}
static string check(string s)
{
if (s.Length > 3)
{
string[] s1 = new string[4];
int k = 0;
string c = "";
foreach (char ch in s)
{
c = c + ch.ToString();
// Console.WriteLine("C :" +c);
if (k == 0)
{
s1[k] = c;
c = "";
k = 1;
}
else
for (int i = 0; i < k; i++)
{
int f = 0;
for (int j = 0; j < k; j++)
{
if (s1[j].Equals(c) || c == "")
f=1;
}
if (f == 1)
break;
s1[k] = c;
c = "";
if (k == 3 && s1[k] != null)
return "YES";
k++;
// Console.WriteLine("K :"+s[k]);
}
}
return "NO";
}
else
{
return "NO";
}
}
}
}
This would be an example which would not work with your algorithm: "aababa". The 4 strings should be ["aa", "b", "a","ba"] given your criteria, but your algorithm always assumes that the first character is the first string in the solution. This assumption is false. If "a" is the first string in the example I give, your algorithm would fail because it would make the first 3 strings ["a", "ab", "aba",...] that last one would fail with your algorithm because it has no more characters to add to the array.
A recursive solution makes sense to me... here's some code that I think would work.
EDIT: it does work... here's a dotnetfiddle
public static List<string> FindStrings(string s, int n) {
if (n == 0) {
if (string.IsNullOrEmpty(s)) {
return new List<string>{ };
}
return null; // null means invalid
}
for (var i=s.Length-1; i>=0; i--){
var startOfString = s.Substring(0, i);
var endOfString = s.Substring(i);
var list = FindStrings(startOfString, n-1);
// invalid... gotta continue to next try
if (list == null) continue;
// make sure there are no matches so far
if (list.Contains(endOfString)) continue;
// bingo!
if (list.Count == n-1) {
list.Add(endOfString);
return list;
}
}
return null; // null means invalid
}
One way to tackle this problem is to solve the problem of creating all possible substrings. Then going through all the possibilities and making sure the results are distinct.
private static void Main(string[] args)
{
var N = int.Parse(Console.ReadLine());
for (var i = 0; i < N; i++)
{
Console.WriteLine(IsPairwiseUnquie(Console.ReadLine(), 4) ? "YES" : "NO");
}
}
public static bool IsPairwiseUnquie(string s, int count)
{
return s.AllSubstrings(4).Any(subs => subs.Count == subs.Distinct().Count());
}
public static IEnumerable<List<string>> AllSubstrings(this string str, int count)
{
if(str.Length < count)
throw new ArgumentException("Not enough characters");
if(count <= 0)
throw new ArgumentException("Must be greater than 0", nameof(count));
// Base case of only one substring, just return the original string.
if (count == 1)
{
yield return new List<string> { str };
yield break;
}
// break the string down by making a substring of all possible lengths from the first n
// then recursively call to get the possible substrings for the rest of the string.
for (int i = 1; i <= str.Length - count + 1; i++)
{
foreach (var subsubstrings in str.Substring(i).AllSubstrings(count - 1))
{
subsubstrings.Insert(0, str.Substring(0, i));
yield return subsubstrings;
}
}
}

How to reverse a string that contains Hebrew letters and numbers?

i have an hebrew string that i need to reverse.
"שורה שלמה בעברית 3/8" וגם נושא חדש בסוגריים (הנושא) וגם מספר בסוגריים (25) וגם נקודה בסוף משפט."
i used this function to reverse it
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
the output is:
".טפשמ ףוסב הדוקנ םגו )52( םיירגוסב רפסמ םגו )אשונה( םיירגוסב שדח אשונ םגו \"8/3 תירבעב המלש הרוש"
as you can see the words in hebrew where reverse successfully but the numbers and () are reversed.
static public string ReverseOnlyHebrew(string str)
{
string[] arrSplit;
if (str != null && str != "")
{
arrSplit = Regex.Split(str, "( )|([א-ת]+)");
str = "";
int arrlenth = arrSplit.Length - 1;
for (int i = arrlenth; i >= 0; i--)
{
if (arrSplit[i] == " ")
{
str += " ";
}
else
{
if (arrSplit[i] != "")
{
int outInt;
if (int.TryParse(arrSplit[i], out outInt))
{
str += Convert.ToInt32(arrSplit[i]);
}
else
{
arrSplit[i] = arrSplit[i].Trim();
byte[] codes = System.Text.ASCIIEncoding.Default.GetBytes(arrSplit[i].ToCharArray(), 0, 1);
if (codes[0] > 47 && codes[0] < 58 || codes[0] > 64 && codes[0] < 91 || codes[0] > 96 && codes[0] < 123)//EDIT 3.1 reverse just hebrew words
{
str += arrSplit[i].Trim();
}
else
{
str += Reverse(arrSplit[i]);
}
}
}
}
}
}
return str;
}
static public string Reverse(string str)
{
char[] strArray = str.ToCharArray();
Array.Reverse(strArray);
return new string(strArray);
}
public static string Reverse(string t)
{
char[] charArray = t.ToCharArray();
string a = "";
int last = 0;
for (int i = 0; i <= charArray.Length-1; i++)
{
if (!IsHebrew(charArray[i]))
{
List<char> temp = new List<char>();
for (; last < i; last++)
{
int k = 0;
temp.Insert(0,charArray[last]);
}
foreach(char g in temp)
{
a += g.ToString();
}
a += charArray[i];
last += 1;
}
}
return a;
}
private const char FirstHebChar = (char)1488; //א
private const char LastHebChar = (char)1514; //ת
private static bool IsHebrew(char c)
{
return c >= FirstHebChar && c <= LastHebChar;
}

Incrementing an alphanumeric string [duplicate]

This question already has answers here:
Iterating through the Alphabet - C# a-caz
(10 answers)
Closed 8 years ago.
I am trying to increment an alphanumeric string using a given charset
say the input is 0000a
then the output should be 0000b
However when the input reaches the defined limit, say zzzzz
it should reset to 00001
I have read the following Increment of Alphabet in c#
using
char c
c++
seem to be the best way to do this.
I have the following class
Namespace BatchNo_Generator
{
class RandomStringGenerator
{
public enum Mode
{
ALPHANUMERIC = 1,
ALPHA = 2,
NUMERIC = 3,
}
public string genbase(int length, string mode)
{
int j = 0;
if (mode == "ALPHANUMERIC")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "0");
j++;
}
s.Insert(s.Length, "1");
return s.ToString();
}
if (mode == "ALPHA")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "a");
j++;
}
s.Insert(s.Length, "a");
return s.ToString();
}
if (mode == "NUMERIC")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "0");
j++;
}
s.Insert(s.Length, "1");
return s.ToString();
}
return "";
}
public string gennext(string current, string mode, char endchar)
{
StringBuilder s = new StringBuilder(current);
int i = current.Length;
if (mode == "ALPHA")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, 'a', mode) == true)
{
s[j] = resetchar(s[j], 'a');
incrementchar(s[j + 1], mode);
}
else
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
break;
}
}
return s.ToString();
}
if (mode == "NUMERIC")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, '0', mode) == true)
{
s[j-1] = resetchar(s[j-1], '0');
incrementchar(s[j - 1], mode);
}
else
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
}
}
return s.ToString();
}
if (mode == "ALPHANUMERIC")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, '0', mode) == true)
{
s[j-1] = resetchar(s[j-1], '0');
char c = incrementchar(s[j - 1], mode);
}
else
{
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
break;
}
}
}
return s.ToString();
}
return "";
}
public char incrementchar(char c, string mode)
{
char cnew = c++;
switch (mode)
{
case "ALPHA":
{
if (char.IsLetter(c) == false) { cnew++; }
else { return char.ToLower(c); }
break;
}
case "NUMERIC":
{
if (char.IsDigit(c) == false) { cnew++; }
else { return c; }
break;
}
case "ALPHANUMERIC":
{
while (char.IsLetterOrDigit(c) == false) { c++; }
// if (char.IsLetterOrDigit(c) == false) { cnew++; }
// else { return char.ToLower(c); }
return char.ToLower(c);
break;
}
}
return '?';
}
public bool checkend(char current, char end, char start, string mode)
{
if (current == end) { return true; }
else { return false; }
}
public char resetchar(char inputchar, char defaultchar)
{
return defaultchar;
}
public static IEnumerable<string> GetColumns(char startchar, char endchar)
{
string s = null;
for (char c2 = startchar; c2 <= endchar + 1; c2++)
{
for (char c = 'A'; c <= 'Z'; c++)
{
if (char.IsLetter(c) == true)
{
yield return s + char.ToLower(c);
}
}
if (char.IsLetterOrDigit(c2) == true)
{
s = c2.ToString();
}
}
}
}
}
Which I tried with
RandomStringGenerator test = new RandomStringGenerator();
MessageBox.Show(test.gennext("0zzzz","ALPHANUMERIC",'0'));
The issue I have is that this input 0zzzz returns 0zzzª
Any help would be appreciated
The code is sloppy I know, i will be cleaning it up when I get a working set
public enum Mode
{
AlphaNumeric = 1,
Alpha = 2,
Numeric = 3
}
public static string Increment(string text, Mode mode)
{
var textArr = text.ToCharArray();
// Add legal characters
var characters = new List<char>();
if (mode == Mode.AlphaNumeric || mode == Mode.Numeric)
for (char c = '0'; c <= '9'; c++)
characters.Add(c);
if (mode == Mode.AlphaNumeric || mode == Mode.Alpha)
for (char c = 'a'; c <= 'z'; c++)
characters.Add(c);
// Loop from end to beginning
for (int i = textArr.Length - 1; i >= 0; i--)
{
if (textArr[i] == characters.Last())
{
textArr[i] = characters.First();
}
else
{
textArr[i] = characters[characters.IndexOf(textArr[i]) + 1];
break;
}
}
return new string(textArr);
}
// Testing
var test1 = Increment("0001", Mode.AlphaNumeric);
var test2 = Increment("aab2z", Mode.AlphaNumeric);
var test3 = Increment("0009", Mode.Numeric);
var test4 = Increment("zz", Mode.Alpha);
var test5 = Increment("999", Mode.Numeric);

Convert integer to binary in C#

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

Categories

Resources