2nd May 2019

Octal Converter

An inline octal to decimal converter that, when given a string with octal values, will convert them to decimal values.

public string ConvertOctalsInString(string inputString)
{
  var regex = new Regex(@"\\\d{3}");
  var matches = regex.Matches(inputString);
  if (matches.Count == 0)
  {
    return inputString;
  }

  var bytes = new List<byte>();
  var lastTail = 0;
  foreach (var match in matches)
  {
    if (lastTail != match.Index)
    {
      var before = inputString.Substring(lastTail, match.Index - lastTail);
      bytes.AddRange(Encoding.UTF8.GetBytes(before));
    }

    var octal = inputString.Substring(match.Index + 1, match.Length - 1);
    var bar = Convert.ToString(Convert.ToInt32(octal), 8);
    bytes.Add(Convert.ToByte(octal, 8));
    lastTail = match.Index + match.Length;
  }

  if (matches.Count >= 1)
  {
    var lastMatch = matches[matches.Count - 1];
    var remaining = inputString.Substring(lastMatch.Index + lastMatch.Length);
    bytes.AddRange(Encoding.UTF8.GetBytes(remaining));
  }

  return Encoding.UTF8.GetString(bytes.ToArray());
}