Return Integers in Base 10 - c#

I've been trying to understand how one would input an integer and have a function return the digits in base 10 in C#. I've researched around and can't find many code examples to work with other than the math formulas.
Thanks!

It sounds like you just want:
int value = 2590123;
string text = value.ToString();
That will automatically use base 10... at least in all the cultures I'm aware of. If you really want to make sure, use the invariant culture:
string text = value.ToString(CultureInfo.InvariantCulture);
Note that the concept of a base only makes sense when you talk about some representation with separate "digits" of some form - such as a string representation. A pure number doesn't have a base - if you have 16 apples, that's the same number as if you've got 0x10 apples.
EDIT: Or if you want to write a method to return the sequence of digits as integers, least significant first:
// Note that this won't give pleasant results for negative input
static IEnumerable<int> GetDigits(int input)
{
// Special case...
if (input == 0)
{
yield return 0;
yield break;
}
while (input != 0)
{
yield return input % 10;
input = input / 10;
}
}

Making a whole lot of assumptions, I'm guessing you want something like this:
// All ints are "base 10"
var thisIsAlreadyBase10 = 10;
Console.WriteLine("The number {0} in base 10 is {0}", thisIsAlreadyBase10);
// However, if you have a string with a non-base 10 number...
var thisHoweverIsAStringInHex = "deadbeef";
Console.WriteLine(
"The hex string {0} == base 10 int value {1}",
thisHoweverIsAStringInHex,
Convert.ToInt32(thisHoweverIsAStringInHex, 16));

Related

C# trying to fill up a binary number to 4 digit blocks

I have a base-n-converter and I wanted it to output all values in 4 digit blocks (1111 -> 1111, 101 -> 0101, 110101 -> 00110101). For this, I made this piece in vscode to try and make it work.
using System;
namespace Test
{
using static intUtilities;
class Program
{
static void Main(string[] args)
{
string number = "";
int[] wholenumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(;;)
{
Console.WriteLine("enter binary number");
number = Console.ReadLine();
Console.WriteLine("is number length divisible by 4? " + Contains(wholenumbers, number.Length/4f));
Console.WriteLine(number.Length/4f);
while(!Contains(wholenumbers, number.Length/4f))
{
number = "0" + number;
}
Console.WriteLine(number);
Console.ReadLine();
}
}
}
public class intUtilities
{
public static bool Contains(int[] array, float number)
{
foreach(int i in array)
{
if(i == number)
{
return true;
}
else {return false;}
}
return false;
}
}
}
For inputting 111, I am expecting an output of 0111, which does happen, but if I input 111111, I am expecting 00111111, but there is no output. When executing the while loop, it should catch the moment when numbers.Length / 4 is "2" (which is when therre would be 8 digits) and break the loop, but for some reason, it doesnt and keeps on adding zeros to the string. It even reads out numbers.Length / 4 as "2" at some point but doesnt break the loop. The code only seems to work for a target size of 4 digits, where numbers.Length / 4 would be "1". Is there a way to correct that? Or even an easier workaround?
There are a number of "interesting" issues with this code, but to answer your immediate question, you need to remove the else {return false;} line. This prevents you from searching over every element in the wholeNumbers array - or more specifically, you only query the first element in the wholeNumbers array (which is the value 1) which is why the code only works correctly for the first 4-bit block of binary digits.
In the spirit of your approach, a possible implementation is:
void Main()
{
string number = "";
Console.WriteLine("enter binary number");
number = Console.ReadLine();
while (number.Length % 4 != 0)
{
number = "0" + number;
}
Console.WriteLine(number);
}
The original question ('why doesn't this work') is answered by Phillip Ngan.
Just fyi the correct result can be gotten in a simple calculation without a loop:
void Main
{
Console.WriteLine("enter binary number");
string number = Console.ReadLine();
int padLength = (4 - (number.Length % 4)) % 4;
number = "000".Substring(0, padLength)+number;
Console.WriteLine(number);
}
edit: Just noticed this is simply a variant for the solution proposed by John Glenn.
Or even an easier workaround?
Relying on the usual "round an integer up to the nearest N" of "integer, divide by N, add one and times by N" we can use this to pad the left of the binary string out to the next "multiple of 4" up from the current length
var x= "01111";
var y = x.PadLeft(((x.Length/4)+1)*4, '0');
y is "00001111";
If you don't like all the parentheses you can use precedence to the same effect
.PadLeft(x.Length/4*4+4, '0');
Hopefully most future readers of the code will remember their high school maths lessons 😀
You can use the modulus function to determine the remainder of one number (the string length) divided by another number (4). The entire effect can be shortened to this:
// find how many characters don't fit into a block of four
int leftovers = numbers.Length % 4;
// determine how many numbers to pad
int padding =
(4 - leftovers) // this is the number of characters we have to add to get an even group of 4
% 4; // this will ensure that if leftovers is 0, then instead of padding 4 characters we don't pad any
// pad the string
string displayMe = numbers.PadLeft(numbers.Length + padding, '0');

Counting Precision Digits

How to count precision digits on a C# decimal type?
e.g. 12.001 = 3 precision digits.
I would like to thrown an error is a precision of greater than x is present.
Thanks.
public int CountDecPoint(decimal d){
string[] s = d.ToString().Split('.');
return s.Length == 1 ? 0 : s[1].Length;
}
Normally the decimal separator is ., but to deal with different culture, this code will be better:
public int CountDecPoint(decimal d){
string[] s = d.ToString().Split(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
return s.Length == 1 ? 0 : s[1].Length;
}
You can get the "scale" of a decimal like this:
static byte GetScale(decimal d)
{
return BitConverter.GetBytes(decimal.GetBits(d)[3])[2];
}
Explanation: decimal.GetBits returns an array of four int values of which we take only the last one. As described on the linked page, we need only the second to last byte from the four bytes that make up this int, and we do that with BitConverter.GetBytes.
Examples: The scale of the number 3.14m is 2. The scale of 3.14000m is 5. The scale of 123456m is 0. The scale of 123456.0m is 1.
If the code may run on a big-endian system, it is likely that you have to modify to BitConverter.GetBytes(decimal.GetBits(d)[3])[BitConverter.IsLittleEndian ? 2 : 1] or something similar. I have not tested that. See the comments by relatively_random below.
I know I'm resurrecting an ancient question, but here's a version that doesn't rely on string representations and actually ignores trailing zeros. If that's even desired, of course.
public static int GetMinPrecision(this decimal input)
{
if (input < 0)
input = -input;
int count = 0;
input -= decimal.Truncate(input);
while (input != 0)
{
++count;
input *= 10;
input -= decimal.Truncate(input);
}
return count;
}
I would like to thrown an error is a precision of greater than x is present
This looks like the simplest way:
void AssertPrecision(decimal number, int decimals)
{
if (number != decimal.Round(number, decimals, MidpointRounding.AwayFromZero))
throw new Exception()
};

Generate a bruteforce string given an offset?

Some years back when I was still a beginner at programming, I found some code online that could generate a bruteforce-code given an offset.
So for instance, if I did GetPassword(1) it would return "a", and if I did GetPassword(2) it would return "b" etc.
Every increment of the offset would provide the next possible combination of strings. A minimum and maximum length of the "password to guess" could also be provided.
Now I have no idea where this code is, or what the algorithm is called. I want to implement one myself, since I need it for URL-enshortening purposes. A user generates a URL that I want to look somewhat long these lines: http://fablelane.com/i/abc where "abc" is the code.
You can think of the output from GetPassword as a number in a different base. For example if GetPassword can output upper and lower case alphanumeric then it is in base 62 -> 26 letters + 26 letters + 10 digits.
GetPassword must convert from base 10 to base 62 in this case. You can use a look up array to find the output characters.
You can convert from one base to another by using an algorithm such as this:
Another stackoverflow post
This is base 26 encoding end decoding:
public static string Encode(int number){
number = Math.Abs(number);
StringBuilder converted = new StringBuilder();
// Repeatedly divide the number by 26 and convert the
// remainder into the appropriate letter.
do
{
int remainder = number % 26;
converted.Insert(0, (char)(remainder + 'a'));
number = (number - remainder) / 26;
} while (number > 0);
return converted.ToString();
}
public static int Decode(string number) {
if (number == null) throw new ArgumentNullException("number");
int s = 0;
for (int i = 0; i < number.Length; i++) {
s += (number[i] - 'a');
s = i == number.Length - 1 ? s : s * 26;
}
return s;
}

Finding the number of places after the decimal point of a Double

I have a Double value:
double a = 4.5565;
What is the easiest way to calculate the number of digits after the decimal point (4 in this case).
I know that I can convert to string and do a split and take the length. But is there an easier way?
There's no easy way, especially since the number of digits mathematically speaking might be far more than displayed. For example, 4.5565 is actually stored as 4.556499999999999772626324556767940521240234375 (thanks to harold for calculating that). You're very unlikely to find a useful solution to this problem.
EDIT
You could come up with some algorithm that works like this: if, as you calculate the decimal representation, you find a certain number of 9s (or zeros) in succession, you round up (or down) to the last place before the series of 9s (or zeros) began. I suspect that you would find more trouble down that road than you would anticipate.
var precision = 0;
var x = 1.345678901m;
while (x*(decimal)Math.Pow(10,precision) !=
Math.Round(x*(decimal)Math.Pow(10,precision)))
precision++;
precision will be equal to the number of significant digits of the decimal value (setting x to 1.23456000 will result in a precision of 5 even though 8 digits were originally specified in the literal). This executes in time proportional to the number of decimal places. It counts the number of fractional digits ONLY; you can count the number of places to the left of the decimal point by taking the integer part of Math.Log10(x). It works best with decimals as they have better value precision so there is less rounding error.
Write a function
int CountDigitsAfterDecimal(double value)
{
bool start = false;
int count = 0;
foreach (var s in value.ToString())
{
if (s == '.')
{
start = true;
}
else if (start)
{
count++;
}
}
return count;
}
I think this might be a solution:
private static int getDecimalCount(double val)
{
int i=0;
while (Math.Round(val, i) != val)
i++;
return i;
}
double val9 = 4.5565d; int count9 = getDecimalCount(val9);//result: 4
Sorry for the duplication -> https://stackoverflow.com/a/35238462/1266873
base on james answer bat much clearer:
int num = dValue.ToString().Length - (((int)dValue).ToString().Length + 1);
num is the exact number of digits after the decimal point.
without including 0 like this(25.520000)
in this case, you will get num= 2
I Think String solution is best : ((a-(int)a)+"").length-2
I'll perhaps use this code if I needed,
myDoubleNumber.ToString("R").Split('.')[1].Length
"R" here is Round Trip Format Specifier
We need to check for the index bounds first of course.
Another solution would be to use some string functions:
private int GetSignificantDecimalPlaces(decimal number, bool trimTrailingZeros = true)
{
var stemp = Convert.ToString(number);
if (stemp.IndexOf(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator) < 0)
return 0;
if (trimTrailingZeros)
stemp = stemp.TrimEnd('0');
return stemp.Length - 1 - stemp.IndexOf(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}
Remember to use System.Windows.Forms to get access to Application.CurrentCulture

C# - Separate integers/strings with division and remainder

I have a homework that I just can't figure out how to do. I'm not sure if the teacher wrote it wrong(he is a bad typer) or if there is a way to accomplish the task.
I work in Visual C# 2010 Express - Console Application
My task is to:
Read a four digit integer, such as 5893, from the keyboard and display the digits separated from one another by a tab each. Use both integer division and modulus operator % to pick off each digit. If the user enters 4567, the output looks like:
4567
4 5 6 7
Sure I know how to separate the numbers by using \t as well as reading the input and displaying it to the user. But how am I supposed to 'pick off' each digit with division and the remainder operators? Maybe he means something else, but not sure.
And another question...
How do I make sure that what the user types in is a number and not a letter?
Do I have to use Char.IsLetter, because I couldn't figure out how to use it on a parsed string.
Example:
string number1;
int x;
Console.Write("Please enter a number to calculate: ");
number1 = Console.ReadLine();
x = Int32.Parse(number1);
What method am I supposed to use and where do i put it in? Because now i only get an error and the application shuts down if I try to enter e letter.
The first question is really more about maths than programming. You know what the division and modulus operators do. Think about how you could use them to get the last (least significant) digit. Once you've done that you can apply a similar technique for the 2nd digit (tens) and then the same for hundreds and thousands and so on.
You've already found Char.IsLetter, but there is also Char.IsDigit, which does what you want more directly. You can do this check for one character and what you have is a string of characters. Have a look at a foreach loop.
System.Int32.TryParse() might be a better choice when converting the String.
Yes, your assignment makes sense. Say you have an integer x = 4567. To pick out the digit at position A you would use:
result = (int)((x / (A * 10)) % 10);
The first part of this (x / (A * 10)) "shifts" x to the right. So a value of A = 1 would divide 4567 by 10 which results in 456.7. You then use the modulo operator "%" to pick out the unit part of that number. Finally you convert to an int to remove the fractional part.
Ok, I won't give the whole solution (after all, this is homework ;)).
This code would check if there's four characters in input:
string input;
do
{
input = Console.ReadLine();
if (input.Length != 4)
Console.WriteLine("You have to enter FOUR digits");
} while (input.Length != 4);
This could be one way of checking the digits:
bool isOk = true;
foreach (char c in input.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("You have to enter four DIGITS");
isOk = false;
break;
}
}
This approach doesn't deal with math but you could do that just as well:
int num = int.Parse(input);
int tensOfThousands = num / 10000;
int thousands = (num - tensOfThousands) / 1000;
int lastDigit = num % 10;
//the rest of the digits are up to you ;)
For everybody new to C#, the solution can be simpler.
// Variables
int number = 1234;
int remainder;
string s = "";
while (number > 0) {
remainder = number % 10;
s = remainder + "\n" + s;
number /= 10;
}
Console.Write (s);

Categories

Resources