Created
August 23, 2011 05:22
-
-
Save nissuk/1164402 to your computer and use it in GitHub Desktop.
C#: 基数変換(2~36)の単純な例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Example | |
{ | |
public class Convert | |
{ | |
/// <summary> | |
/// 値を指定した基数で等価の String 形式に変換します。 | |
/// 負数の場合はSystem.Convert.ToString(x, Int32)とは違い正数として変換したのち、頭に"-"を付けます。 | |
/// </summary> | |
/// <param name="value">変換する値</param> | |
/// <param name="toBase">戻り値の基数。2~36である必要があります。</param> | |
/// <returns></returns> | |
public static string ToString(long value, int toBase) | |
{ | |
if (toBase <= 1 || 37 <= toBase) throw new ArgumentException(); | |
string sign = ""; | |
if (value < 0) { | |
value *= -1; | |
sign = "-"; | |
} | |
if (toBase <= value) return sign + ToString(value / toBase, toBase) + ToString(value % toBase, toBase); | |
else if (10 <= value) return sign + (char)(87 + value); | |
return sign + value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
再帰しない方法に書き換えたものを後日上げます…