[英]How to convert base 10 negative number to base 8 conversion without using Convert.To() method?
How can i represent decimal negative number in octal without using Convert.To()
method?如何在不使用Convert.To()
方法的情况下以八进制表示十进制负数?
public static string GetOctal(int number)
{
int base = 8;
}
So for example:例如:
-3 (base 10) = 37777777775 (base 8) -3(基数 10)= 37777777775(基数 8)
But what algorithm should i use to get this result?但是我应该使用什么算法来获得这个结果?
The are test cases for my task:这些是我的任务的测试用例:
[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);
You can always go the source code of the Convert
class at source.dot.net here and follow ParseNumber
's IntToString
method:您始终可以在 source.dot.net 上 go Convert
class的源代码,并遵循ParseNumber
的IntToString
方法:
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; (...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.