开发者

Easily calculating and listing binary combinations

开发者 https://www.devze.com 2023-02-20 17:28 出处:网络
I have 5 bits and so 32 different combinations (of them). Starting from 00000 and ending with 11111 Is there some way of quickly listing all possibilities? 开发者_运维问答I could do it by hand,

I have 5 bits and so 32 different combinations (of them).

Starting from

00000

and ending with

11111

Is there some way of quickly listing all possibilities? 开发者_运维问答I could do it by hand, but I worry that I might miss one. I'm guessing some clever chap has written some algorithm and/or made a website, that can do this very easily. At least I hope so.

Thanks a lot.


This will put them all on the command line on Linux.

echo {0..1}{0..1}{0..1}{0..1}{0..1}


In Ruby:

0b0000.upto(0b1111) {|n| puts n.to_s(2).rjust(4,"0")}
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


Write a column with integer from 0 to 31, then write a second column with the binary equivalent of each integer side-by-side.

That way you will increase your chance not to miss a combination.


Just count from 0 to 31 and output the digit in it's binary form.

Something like this should do:

public static String zeroPad(String str) {
    return "00000".substring(str.length()) + str;
}

public static void main(String[] args) {
    for (int i = 0; i < 32; i++)
        System.out.printf("%s%n", zeroPad(Integer.toBinaryString(i)));
}

Output:

00000
00001
00010
00011
...
11110
11111


for (int i = 0; i <31; i++) cout << ((i & 16) >> 4) << ((i & 8) >> 3) << ((i & 4) >> 2) << ((i & 2) >> 1) << (i & 1) << endl;


Unix:

echo {0..1}{0..1}{0..1}{0..1} | xargs -n 1
0

精彩评论

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