如何在不使用 Convert.To() 方法的情况下将基数为 10 的负数转换为基数为 8 的转换?

问题描述

如何在不使用 Convert.To() 方法的情况下以八进制表示十进制负数?

public static string GetOctal(int number)
{     
   int base = 8;    
}

例如:

-3(基数 10)= 37777777775(基数 8)

但是我应该使用什么算法来得到这个结果?

我的任务的测试用例:

        [TestCase(-3,8,ExpectedResult = "37777777775")]
        [TestCase(-127,ExpectedResult = "37777777601")]
        [TestCase(-675432,ExpectedResult = "37775330630")]
        [TestCase(-1908345,ExpectedResult = "37770560607")]
        [TestCase(int.MinValue,ExpectedResult = "20000000000")]
        [TestCase(-3,16,ExpectedResult = "FFFFFFFD")]
        [TestCase(-127,ExpectedResult = "FFFFFF81")]
        [TestCase(-675432,ExpectedResult = "FFF5B198")]
        [TestCase(-1908345,ExpectedResult = "FFE2E187")]
        [TestCase(int.MinValue,ExpectedResult = "80000000")]
        [TestCase(1908345,10,ExpectedResult = "1908345")]
        [TestCase(int.MaxValue,ExpectedResult = "2147483647")]
        public string GetRadix_Tests(int number,int radix) => number.GetRadix(radix);

解决方法

您可以随时访问 source.dot.net here 上的 Convert 类的源代码并遵循 ParseNumberIntToString 方法:

public static string IntToString(int n,int radix,int width,char paddingChar,int flags)
{
    Span<char> buffer = stackalloc char[66]; // Longest possible string length for an integer in binary notation with prefix

    if (radix < MinRadix || radix > MaxRadix)
        throw new ArgumentException(SR.Arg_InvalidBase,nameof(radix));

    // If the number is negative,make it positive and remember the sign.
    // If the number is MIN_VALUE,this will still be negative,so we'll have to
    // special case this later.
    bool isNegative = false;
    uint l;
    if (n < 0)
    {
        isNegative = true;
    (...)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...