首页 > 代码库 > c#工具类之Int扩展类
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 =http://www.mamicode.com/= 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扩展类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。