开发者

What's the easiest way to get the binary representation of an integer?

开发者 https://www.devze.com 2023-01-13 23:30 出处:网络
Actually, I\'m not asking how to implement this functionality myself. I know it wouldn\'t be very complicated. I just don\'t want to reinvent the wheel, so I was wondering if this functionality exists

Actually, I'm not asking how to implement this functionality myself. I know it wouldn't be very complicated. I just don't want to reinvent the wheel, so I was wondering if this functionality exists somewhere in the BCL. It seems like surely it's there somewhere...

Example input/desired output:

Input       Output
1           1
2       开发者_如何学C    10
3           11
4           100
10          1010


How about System.Convert.ToString(int value, int toBase) with toBase set to 2?


Try Convert.ToString, like this:

Console.WriteLine(Convert.ToString(1, 2));
Console.WriteLine(Convert.ToString(2, 2));
Console.WriteLine(Convert.ToString(3, 2));
Console.WriteLine(Convert.ToString(4, 2));
Console.WriteLine(Convert.ToString(10, 2));

The second parameter is the base to use to convert the number (in this case, base 2).

0

精彩评论

暂无评论...
验证码 换一张
取 消