简体   繁体   中英

Get the n digit binary representation of a number

I have tried this way to get the binary representation in C#

int i = 1;
string binary = Convert.ToString(i, 2);

it returns a single char string "1"

i need an digit string suppose the number is 8 ni want a 5 digit binary representation,

i need it to be "01000"

number of digits (n) is the input.

Thanks

string binary = Convert.ToString(i, 2).PadLeft(5, '0');

You can do it by this.

string str = Convert.ToString(8, 2).PadLeft(5, '0');

PadLeft is used to put the 0 on left of expression here we have given 5 is totol width of number. and second parament is character to put on left when number is less then 5 characters

Rolling your own, you could use something like this (not tested, but I think this should work):

int i = 8; // your number
int noZeros = 5;
StringBuilder sb = new StringBuilder();
while(i != 0 && noZeros > 0){
    if(i & 1 != 0){ sb.Insert(0, "1"); }
    else { sb.Insert(0, "0"); }
    i = i >> 1;
    noZeros --;
}

string binary = sb.ToString();

That should work for any int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM