Convert octal string to an integer number in C#

C# Convert octal string to an integer: Here, we will figure out how to change over a given string that contains an octal number in an integer number?

Given an octal string and we need to change over it into an integer number.

Changing over from octal string to integer

Let guess you have a string “30071” which is an octal value of integer 12345, however, this value is in string arrangement, and you need to its integer (number) value.

To change over an octal string to an integer number – we use Convert.ToInt32() strategy.

Syntax:

Convert.ToInt32(input_string, Input_base); 

Here,

  • input_string is the information containing an octal number in a string group.
  • input_base is the base of the information value – for an octal value, it will be 8.

Example:

    Input: "30071"
    Function call:
    Convert.ToInt32(input, 8);
    Output:
    12345

    Input: "3007A" //not 'A' is not an octal number digit
    Function call:
    Convert.ToInt32(input, 8);
    Output:
    Exception

Code:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //octal number as string
            string input = "30071";
            int output = 0;
            //converting to integer 
            output = Convert.ToInt32(input, 8);
            //printing the value
            Console.WriteLine("Integer number: " + output);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

    Integer number: 12345

Example with Exception handling

Code:

using System;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            int output = 0;
            try
            {
                //input string
                Console.Write("Enter an octal number: ");
                input = Console.ReadLine();

                //converting to integer
                output = Convert.ToInt32(input, 8);

                Console.WriteLine("Integer number: " + output);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

First run with valid input:
Enter an octal number: 30071
Integer number: 12345

Second run with invalid input:
Enter an octal number: 3007A
System.FormatException: Additional non-parsable characters are at the end of the
 string.
   at System.ParseNumbers.StringToInt(String s, Int32 radix, Int32 flags, Int32*
 currPos)
   at System.Convert.ToInt32(String value, Int32 fromBase)
   at ConsoleApplication3.Program.Main(String[] args) in F:\Ankur\RunningHeart\Con
soleApplication3\ConsoleApplication3\Program.cs:line 19

Leave a Comment

error: Alert: Content is protected!!