На вход подается десятичное стознаковое число. На выходе это же число в восьмеричной системе. Помогите придумать алгоритм перевода стознакового числа в восьмеричную систему. Видимо придется работать со строкой и ее частями, потому что C# не умеет работать с числами данной длины. Но не понятно как потом все правильно сложить и вывести, чтобы получить верный результат.
1 ответ
- разобрать исходную строку в
BigInteger
(добавить Reference на сборкуSystem.Numerics
и using на неймспейсSystem.Numerics
) - преобразовать этот
BitInteger
в массив байт - собрать байты по 3 (24 бита, 8 восьмеричных символов) и преобразовать в строку
- склеить полученную строку
using System;
using System.Numerics;
using System.Text;
public static class BigIntegerExtensions
{
/// <summary>
/// Converts a <see cref="BigInteger"/> to a octal string.
/// </summary>
/// <param name="bigint">A <see cref="BigInteger"/>.</param>
/// <returns>
/// A <see cref="System.String"/> containing an octal
/// representation of the supplied <see cref="BigInteger"/>.
/// </returns>
public static string ToOctalString(this BigInteger bigint)
{
var bytes = bigint.ToByteArray();
var idx = bytes.Length - 1;
// Create a StringBuilder having appropriate capacity.
var base8 = new StringBuilder(((bytes.Length / 3) + 1) * 8);
// Calculate how many bytes are extra when byte array is split
// into three-byte (24-bit) chunks.
var extra = bytes.Length % 3;
// If no bytes are extra, use three bytes for first chunk.
if (extra == 0)
{
extra = 3;
}
// Convert first chunk (24-bits) to integer value.
int int24 = 0;
for (; extra != 0; extra--)
{
int24 <<= 8;
int24 += bytes[idx--];
}
// Convert 24-bit integer to octal without adding leading zeros.
var octal = Convert.ToString(int24, 8);
// Ensure leading zero exists if value is positive.
if (octal[0] != '0' && bigint.Sign == 1)
{
base8.Append('0');
}
// Append first converted chunk to StringBuilder.
base8.Append(octal);
// Convert remaining 24-bit chunks, adding leading zeros.
for (; idx >= 0; idx -= 3)
{
int24 = (bytes[idx] << 16) + (bytes[idx - 1] << 8) + bytes[idx - 2];
base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0'));
}
return base8.ToString();
}
}
namespace ConsoleApplication47
{
class Program
{
static void Main(string[] args)
{
BigInteger value = BigInteger.Parse("2");
Console.WriteLine(value.ToOctalString());
}
}
}
код взят с enSO: Convert BigInteger to decimal, hex, binary, octal string
Если не нужно поддерживать отрицательные значения - уберите часть кода, добавляющую leading zero.
-
24 бита, 4 восьмеричных символа
это верно написано? 24 бита - это ведь 24/3=8, 8 восьмеричных символа? 28 янв 2016 в 10:38 -
@AlexceiShmakov да, спасибо, ошибся. исправил.– user17722128 янв 2016 в 11:25
-
BigInteger
справляется и с миллионом десятичных знаков.