【问题标题】:How to convert base 10 negative number to base 8 conversion without using Convert.To() method?如何在不使用 Convert.To() 方法的情况下将基数 10 负数转换为基数 8 转换?
【发布时间】:2021-05-01 20:06:57
【问题描述】:

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

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

例如:

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

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

这些是我的任务的测试用例:

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

【问题讨论】:

  • 这能回答你的问题吗? C# Decimal To Octal
  • 37777777775(octal) 不是负数(这也是八进制的 -3)。所以这可能是 (uint)number 转换的。
  • @Klaus Gütter 请看我添加的测试用例
  • @Fabjan 不,因为没有转换有符号负数的算法。
  • @AliaksandrAfiarouski 也根据测试用例,似乎预期的结果是将(uint)number 转换为给定的基数。所以转换本身不必处理负数。

标签: c# .net algorithm type-conversion base-conversion


【解决方案1】:

您可以随时在 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;
    (...)

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多