1

I want to split a 40 digit number and send each digit into an array called digits. ToArray doesn't work because it can't convert from char to int. Neither does Split I think? I'm stumped

edit: These are the instructions: Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. Provide methods Input, ToString, Add and Subtract. For comparing HugeInteger objects, provide the following methods: IsEqualTo, IsNotEqualTo, IsGreaterThan, IsLessThan, IsGreaterThanOrEqualTo and IsLessThanOrEqualTo. Each of these is a method that returns true if the relationship holds between the two HugeInteger objects and returns false if the relationship does not hold. Provide method IsZero. In the Input method, use the string method ToCharArray to convert the input string into an array of characters, then iterate through these characters to create your HugeInteger.

7
  • What data type is your 'number', and I assume the array you want to cast your 'number' to is of type int? Commented Dec 5, 2018 at 21:01
  • You need to use int.Parse or int.TryParse on each character. Commented Dec 5, 2018 at 21:02
  • 3
    int[] digits = "12345".Where(char.IsNumber).Select(c => int.Parse(c.ToString())).ToArray(); Commented Dec 5, 2018 at 21:03
  • Is your number stored as a string? int? double? Commented Dec 5, 2018 at 21:28
  • @Captain Wibble I think I'm going to be using a string and yes the array will be int Commented Dec 5, 2018 at 21:34

4 Answers 4

5
string digits = "8957853759876839473454789595495735984339";
int[] array = digits.Select(x => (int)char.GetNumericValue(x)).ToArray();

Or

int[] array = digits.Select(x => x - 48).ToArray();

As @Haldo requested explanation about why this one should work, It is because char is implicitly castable to int. Live Demo

If you want to avoid getting Exception if there are characters that can not be parsed as numbers, you may ignore them:

int[] array = digits.Where(x => char.IsNumber(x)).Select(x => x - 48).ToArray();
Sign up to request clarification or add additional context in comments.

9 Comments

Why not just use Char.GetNumericValue(x) like it was intended?
Note that if there's any doubt that a character won't be a number and you don't want to throw an exception, add a .Where(char.IsNumber) between digits and .Select.
@AshkanMobayenKhiabani Yeah, I know...but often what we expect or assume to be true isn't always the case. Was just a note to the OP if they wanted to avoid a possible exception.
@AshkanMobayenKhiabani Thanks! I wasn't doubting that it works, I was just curious as to why. I looked into it, it's because each char is represented as an integer internally. '0' has the value 48, so the subtraction automatically casts to int eg '9' - '0' = 57 - 48 = 9. I think!
@hadlo you are welcome. as char.MinValue to char.MaxValue all in int range so an implicit cast is set for it, but the opposite is not true, same goes for casting byte to int, ...
|
1

You can use Select extension method to transform the characters into integers:

int[] result = str.Select(x => int.Parse(x.ToString()))
                  .ToArray();

or assuming there could be invalid characters:

int[] result = str.Where(char.IsDigit)
                  .Select(x => int.Parse(x.ToString()))
                  .ToArray();

Comments

1

To handle huge number the best way is to convert string of integers to an array of bytes. So code converts the decimal number to binary byte[] array. Is uses the method that is taught in school to do base conversion from decimal to hex using long division.

I tested code thoroughly by using every number between 0 and 2^24.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication89
{
    class Program
    {
        static void Main(string[] args)
        {

            string digits = "8957853759876839473454789595495735984339";
            List<byte> results = Binary.GetBytes(digits);
            //test code
            //for (int i = 0; i < (Math.Pow(2,24)); i++)
            //{
            //    string digits = i.ToString();
            //    Console.WriteLine(i);
            //    List<byte> results = Binary.GetBytes(digits);
            //    long value = results.Select((x, j) => x << (j * 8)).Sum();
            //    if (i != value)
            //    {
            //        int a = 3;
            //    }
            //}
        }


    }
    public class Binary
    {
        public static List<byte> GetBytes(string input)
        {
            List<byte> results = new List<byte>();
            string divisorStr = input;


            int nibbleCount = 0;


            while (divisorStr.Length != 0)
            {
                int number = 0;
                string quotentStr = "";
                byte carry = 0;

                //divide a string by 16 to get remainders
                while (divisorStr.Length != 0)
                {
                    number = (carry * 10) + int.Parse(divisorStr.Substring(0, 1));
                    divisorStr = divisorStr.Substring(1);
                    if (divisorStr.Length == 0) exit = true;

                    int digit = number / 16;
                    if (quotentStr != "" | (digit != 0))
                    {
                        quotentStr += digit.ToString();
                    }
                    carry = (byte)(number % 16);
                }
                ///combine the remainders together into an array of bytes
                if (nibbleCount % 2 == 0)
                {
                    results.Add(carry);
                }
                else
                {
                    results[results.Count - 1] |= (byte)(carry << 4);
                }
                divisorStr = quotentStr;
                nibbleCount++;
            }
            return results;
        }
    }
}

Comments

-3

Since you want it into just a char array, why not just call .ToString() on the int then call .ToCharArray()?

int nums = 123456789;

char[] numss = nums.ToString().ToCharArray();

foreach(char n in numss) {
    Console.Write(string.Format("{0} ", n));
}
// 1 2 3 4 5 6 7 8 9... 

Since I misread the question and everybody is using the Select extension, why not just use a simple for loop and convert them to int.

string nums = "12345";
int [] digits = new int[nums.Length];

for(int i = 0; i < nums.Length; i++) {
    digits[i] = Convert.ToInt32(Char.GetNumericValue(nums[i]));
}

foreach(int n in digits) {
    Console.Write(string.Format("{0} ", n));
}
// 1 2 3 4 5

3 Comments

OP wants an int array, not a char array
The OP is starting with a string of numbers, and wants to convert it to an array of integers.
Fixed. Didn't see the actual type of the result array as it was in the question title.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.