1

I'm trying to convert a random string into an octal int32. If someone would give ABCD i would want to get 101 102 103 104. I tried int i = Convert.ToInt32("ABCD", 8);

  • Why would A convert to 101? Why would you assume this is octal? – Mithrandir Jun 23 '21 at 14:15
  • Maybe convert to ASCII Numbers first? – KYL3R Jun 23 '21 at 14:16
  • 1
    @Mithrandir octal 101 = decimal 65 = ASCII code of 'A' – Klaus Gütter Jun 23 '21 at 14:17
  • 1
    split your word/string into letters/char array (like here https://stackoverflow.com/questions/4246856/how-do-i-split-a-words-letters-into-an-array-in-c ) and call `Convert.ToInt32(arr[i], 8)` foreach letter – demo Jun 23 '21 at 14:17
  • @KlausGütter I guessed that the stated intent was quite different though. – Mithrandir Jun 23 '21 at 14:19
  • _"Convert.ToInt32("ABCD", 8)"_ doesn't work as you expected. This would try to parse a value to the base 8 that is represented as string into a int32. So, it accepts only characters 0 to 7. And that's also why feeding it the ASCII value won't work: https://dotnetfiddle.net/Wf9Sv9 – Fildor Jun 23 '21 at 14:25

3 Answers3

2

You need multiple steps:

  • Get the bytes of your inpout string (I'll assume ASCII encoding)
  • Format the bytes in octal notation
  • Join the octals to get a single result (optional)
string input = "ABCD";
var bytes = Encoding.ASCII.GetBytes(input); // 65,66,67,68
var octals = bytes.Select(p => p.FormatOctal()).ToArray(); //101,102,103,104
var result = string.Join(" ", octals); //"101 102 103 104"

Helper to format a byte in octal representation

public static class MyExtensions
{
    public static string FormatOctal(this byte value)
    {
        return Convert.ToString(value, 8);
    }
}
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
2

As there are no octal integer literals in C# as it is mentioned here Octal equivalent in C#. You could use strings to display/work with octal numbers. For example this way:

string text = "ABCD";
foreach (char c in text)
{
    var octalString = Convert.ToString(c, 8);
    Console.WriteLine(octalString);
}

Console output is: 101 102 103 104

René
  • 100
  • 1
  • 8
0

If you need a string containing octal equivalents, you can run this:

var s = "ABCD"
    .Select(c => Convert.ToInt32(c))
    .Select(v => Convert.ToString(v, 8))
    .Aggregate((v0, v1) => $"{v0} {v1}");

And if you need the integers representing octal values (I wouldn't recommend that) you can convert the string representation back to integers and store them in an array:

var i = "ABCD"
    .Select(c => Convert.ToInt32(c))
    .Select(v => Convert.ToString(v, 8))
    .Select(v => Convert.ToInt32(v))
    .ToArray();
Mike
  • 1,225
  • 10
  • 21