c#工具类之Int扩展类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#工具类之Int扩展类相关的知识,希望对你有一定的参考价值。
public static class IntHelper { /// <summary> /// 转换为2进制字符串 /// </summary> /// <param name="num"></param> /// <returns></returns> public static string To2Base(this int num) { return Convert.ToString(num, 2); } /// <summary> /// 转换为8进制字符串 /// </summary> /// <param name="num"></param> /// <returns></returns> public static string To8Base(this int num) { return Convert.ToString(num, 8); } /// <summary> /// 转换为16进制字符串 /// </summary> /// <param name="num"></param> /// <returns></returns> public static string To16Base(this int num) { return Convert.ToString(num, 16); } /// <summary> /// 2进制字符串转换为int /// </summary> /// <param name="numStr"></param> /// <returns></returns> public static int From2Base(this string numStr) { return Convert.ToInt32(numStr, 2); } /// <summary> /// 8进制字符串转换为int /// </summary> /// <param name="numStr"></param> /// <returns></returns> public static int From8Base(this string numStr) { return Convert.ToInt32(numStr, 8); } /// <summary> /// 16进制字符串转换为int /// </summary> /// <param name="numStr"></param> /// <returns></returns> public static int From16Base(this string numStr) { return Convert.ToInt32(numStr, 16); } /// <summary> /// 将自然数转换了N进制字符串 /// </summary> /// <param name="number">自然数</param> /// <param name="xBase">N进制(2~36之间)</param> /// <returns>N进制字符串</returns> public static string ToXBase(this int number, int xBase) { if (xBase < 2 || xBase > 36) { throw new ArgumentOutOfRangeException("参数值不在2~36的范围内"); } if (xBase == 10) return number.ToString(); int n = xBase; int q = number; int r; string rtn = ""; while (q >= n) { r = q % n; q = q / n; if (r < 10) rtn = r.ToString() + rtn; else rtn = Convert.ToChar(r + 55).ToString() + rtn; } if (q < 10) { rtn = q.ToString() + rtn; } else { rtn = Convert.ToChar(q + 55).ToString() + rtn; } return rtn; } /// <summary> /// 判断是否为素数 /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsPrime(this ulong value) { //质数(素数)定义为在大于1的自然数中 if (value > 1) { //除了2的偶数都是合数 if (value.IsEvenNumber()) { //2是特殊的素数 return value == 2; } for (ulong i = 3; (i * i) <= value; i += 2) { if ((value % i) == 0) { return false; } } return value != 1; } return false; } /// <summary> /// 是否是偶数 /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsEvenNumber(this long value) { if (value < 0) { value = value * -1; } //value & 1==0则必为偶数 return (value & 1) == 0; } /// <summary> /// 是否是偶数 /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsEvenNumber(this ulong value) { //value & 1==0则必为偶数 return (value & 1) == 0; } /// <summary> /// 是否是奇数 /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsOddNumber(this ulong value) { //value & 1==0则必为偶数 return (value & 1) > 0; } }
以上是关于c#工具类之Int扩展类的主要内容,如果未能解决你的问题,请参考以下文章