1 Star 0 Fork 65

欢喜派 / C-Sharp

forked from 编程语言算法集 / C-Sharp 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Int2Binary.cs 2.63 KB
一键复制 编辑 原始数据 按行查看 历史
Andrii Siriak 提交于 2021-05-08 21:42 . Cleanup minor things (#221)
using System.Text;
namespace Algorithms.Other
{
/// <summary>
/// Manually converts an integer of certain size to a string of the binary representation.
/// </summary>
public static class Int2Binary
{
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(ushort input)
{
ushort msb = ushort.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 16; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(uint input)
{
var msb = uint.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 32; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
/// <summary>
/// Returns string of the binary representation of given Int.
/// </summary>
/// <param name="input">Number to be converted.</param>
/// <returns>Binary representation of input.</returns>
public static string Int2Bin(ulong input)
{
var msb = ulong.MaxValue / 2 + 1;
var output = new StringBuilder();
for (var i = 0; i < 64; i++)
{
if (input >= msb)
{
output.Append("1");
input -= msb;
msb /= 2;
}
else
{
output.Append("0");
msb /= 2;
}
}
return output.ToString();
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/Joypai/C-Sharp.git
git@gitee.com:Joypai/C-Sharp.git
Joypai
C-Sharp
C-Sharp
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891