Search code examples
c#decimaloctal

Strange FormatException when converting to octal


So I have an integer number 208 I don't expect many to understand why I am doing this, but the end result of what I am trying to do is get the base-10 representation of octal number 208 (two-zero-eight). I expect that the confusing thing (for people that will try and answer this question) is that while 208 is an integer, I am using it more like a string containing the characters two, zero, and eight. Please let me know if there are any more questions on this, as I think it will cause some confusion.

Anyway, to get the base-10 representation of "208" here is what I do:

  1. Convert int 208 into string "208".
  2. Take the string "208", and parse from octal to decimal.

Then, here is the corresponding source code:

public byte OctalToDecimal(int octalDigits)
{
    byte decimalValue = 0;
    string octalString = string.Empty;

    // first, get a string representation of the integer number
    octalString = octalDigits.ToString();

    // now, get the decimal value of the octal string
    decimalValue = Convert.ToByte(octalString, 8);

    // set the decimal-value as the label
    return decimalValue;
}

I get a format exception when octalDigits = 208. I get a message about there being additional characters in the octalString's value. Why would that be? All I do is convert from int to string it's very short/simple, and not like I append anything on there. What is going on?


Solution

  • You should know that the digits for octal numbers are in the range 0 to 7

    Here, some helpful links

    the octal representations of bytes range from 000 to 377?

    http://www.asciitable.com/