Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
3.00/5 (4 votes)
See more:
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????
Posted
Comments
Sergey Alexandrovich Kryukov 9-May-12 17:51pm    
Why? Do you understand that your strings are not numbers? How about using with data, not with strings representing numbers? What is the goal of it?
--SA
Sergey Alexandrovich Kryukov 9-May-12 17:53pm    
Your problem does not seem to make any practical sense, but what prevents you from having all strings of the same length? You could start form 0-filled string of required length.
--SA
sonal_1785 9-May-12 18:16pm    
My motive is to calculate Hamming distance. for that length of the string should be equal. eg
110011001
101010101XOR
011001100

I think it is what you want.

C#
Random rnd = new Random();
            int number = rnd.Next(64);
            string retVal = Convert.ToString(number, 2);
            retVal = retVal.PadLeft(6, '0');
            MessageBox.Show(retVal);
 
Share this answer
 
Comments
sonal_1785 9-May-12 21:12pm    
thanks for the help....this is exactly i was looking for.
aidin Tajadod 10-May-12 12:25pm    
Happy to help.
The following will give you the number of bits you need for a number:

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


Just add one to get the length that will always start with a 0.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900