如何在C#中设置二进制数的长度 [英] How to set the length of Binary Number in C#

查看:314
本文介绍了如何在C#中设置二进制数的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,需要在其中生成一个随机二进制数.每个二进制数的长度应固定为6,例如. 55 ="110111"的大小为6,但10 ="1010"
所以要使其大小等于6,我想在右边添加零,它看起来应该像
10 ="001010"代替"1010".
因此,如何设置二进制数的长度????

I am developing a program where I need to generate a random binary number. each binary number should have fixed length of 6 in size eg. 55= "110111" size is 6 but 10="1010"
so to make its size equal to 6 I want to add zero on right and it should look like
10="001010" instead of "1010".
So,How to set the length of binary number????

推荐答案

我认为这是您想要的.

I think it is what you want.

Random rnd = new Random();
            int number = rnd.Next(64);
            string retVal = Convert.ToString(number, 2);
            retVal = retVal.PadLeft(6, '0');
            MessageBox.Show(retVal);


以下内容将为您提供数字所需的位数:

The following will give you the number of bits you need for a number:

int n = 6;
var len =Math.Round (Math.Pow(n + 1, .5) + .5);



只需加一个就可以得到始终以0开头的长度.



Just add one to get the length that will always start with a 0.


这篇关于如何在C#中设置二进制数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆