下面为C#实现的各个进制互转等帮助类方法
/// <summary> /// 二进制字符串转byte[] /// </summary> /// <param name="binaryStr"></param> /// <returns></returns> public static byte[] ConvertBinaryStringToBytes(string binaryStr) { binaryStr = binaryStr.Replace("-", string.Empty); binaryStr = BinaryLengthAppendTo8(binaryStr); byte[] resultantArray = new byte[binaryStr.Length / 8]; for (int i = 0; i < resultantArray.Length; i++) { var str = binaryStr.Substring(i * 8, 8); resultantArray[i] = Convert.ToByte(str, 2); } return resultantArray; } /// <summary> /// 二进制字符串转base64 /// </summary> /// <param name="binaryStr"></param> /// <returns></returns> public static string ConvertBinaryStringToBase64(string binaryStr) { var byteArr = ConvertBinaryStringToByteArr(binaryStr); return Convert.ToBase64String(byteArr); } /// <summary> /// 10进制转二进制字符串("100010010"格式) /// </summary> /// <param name="num"></param> /// <returns></returns> public static string ConvertDoubleToString(double num) { List<string> binary = new List<string>(); while (num > 0) { double tmp = num; num = Math.Floor(tmp / 2); binary.Add((tmp % 2).ToString()); } binary.Reverse(); return string.Join(string.Empty, binary); } /// <summary> /// btye[]转二进制字符串 /// </summary> /// <param name="bindata"></param> /// <returns></returns> public static string ConvertBinaryToString(byte[] bindata) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bindata.Length; i++) { string hv = Convert.ToString(bindata[i], 2); hv = BinaryLengthAppendTo8(hv); sb.Append(hv); } return sb.ToString(); } public static byte[] ConvertDoubleToBytes(double num) { return ConvertBinaryStringToByteArr(ConvertDoubleToString(num)); } /// <summary> /// 转换bindata到十进制double(强转溢出后返回-1) /// </summary> /// <param name="bindata"></param> /// <returns></returns> public static double ConvertBinaryToDouble(byte[] bindata) { string binary = ConvertBinaryToString(bindata); return ConvertBinaryStrToDouble(binary); } /// <summary> /// 转换"10101010"到十进制double(强转溢出后返回-1) /// </summary> /// <param name="binaryStr"></param> /// <returns></returns> public static double ConvertBinaryStrToDouble(string binaryStr) { try { int binLen = binaryStr.Length; double sum = 0; for (int i = 0; i < binLen; i++) { if (binaryStr[i] == '1') { sum += Math.Pow(2, binLen - i - 1); } } if (double.IsInfinity(sum)) { throw new Exception("溢出"); } return sum; } catch { return -1; } } private static string BinaryLengthAppendTo8(string binaryStr) { int m = binaryStr.Length % 8; if (m != 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 8 - m; i++) { sb.Append("0"); } binaryStr = sb.ToString() + binaryStr; } return binaryStr; }
作者:太白菜Rennbon
链接:https://www.jianshu.com/p/5bb02d0641e8
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦