如何在一行代码中生成一个8位长的0和1的随机字符串?

时间:2017-10-27 00:37:02

标签: java

public class Main {
        public static void main(String[] args) {
                // generate a random String of 0's and 1's that is 8 digits long
                System.out.println("Print the string of 0's and 1's");
        }
    }
  

我想只在一行,只有一行代码。

8 个答案:

答案 0 :(得分:2)

如果您不想包含以0开头的二进制数字,例如'00001010',并且您只想表示以1开头的二进制数,那么您在128和255之间'播放',导致10000000 = 128十进制和11111111 = 255在这种情况下你需要做这样的事情:

https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.jpg

Math.random()给你一个0.0和1.0的数字,所以127 * Math.random会给你一个[0,127]之间的随机值,因为我们想用'1'开始我们的二进制数,那么肯定是数字必须大于128 = 10000000。

如果您想要包含0到255之间的所有数字,您可以这样做:

https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.webp

答案 1 :(得分:2)

您也可以使用options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"]) options.add_argument('--disable-gpu') options.add_argument('--headless') chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe" 执行此操作。它不是一个很好的解决方案,因为它实例化了几个IntStream对象,但是它的一行代码:

Random

答案 2 :(得分:2)

您可以使用RandomStringUtils并指定所需的字符。

System.out.println(RandomStringUtils.random(8, '0', '1'));

答案 3 :(得分:1)

这是一行,尽管它绝对不是最易读的方式。大多数事情都可以在一行中完成,但不容易一目了然地调试或理解。这也不是最快的方法,但是你说你不关心效率。

String random8Bits = new Random().ints(8, 0, 2).mapToObj(Integer::toString).collect(Collectors.joining());

工作原理:

new Random()
// creates a random number generator
.ints(8, 0, 2)
// returns an IntStream containing 8 random numbers between 0 (inclusive) and 2 (exclusive).
.mapToObj(Integer::toString)
// converts each int in the stream to its string representation
.collect(Collectors.joining())
// joins the strings

有关详细信息,请参阅Random.ints(long, int, int)IntStreamCollectors.joining()

答案 4 :(得分:0)

您想使用Class Integer的toBinaryString方法。然后通过应用&amp ;,将它短接到一个字节(8位),然后传递一个新的随机值。 0xFF的。

System.out.println(Integer.toBinaryString(128 + (int) (127 * Math.random())));

答案 5 :(得分:0)

我们可以随机选择一个包含8位数字的数字并打印出来:

    int n = ThreadLocalRandom.current().nextInt(128, 256);
    System.out.println(Integer.toBinaryString(n));

我们希望数字大于127,否则我们不会有8位(出于同样的原因,我们希望它小于256)。

答案 6 :(得分:0)

只是另一种解决方案:

String.format("%8s", Integer.toBinaryString(new Random().nextInt() & 0xFF)).replace(' ', '0')

没有流,单Random,但有String操作......

答案 7 :(得分:0)

这是另一个“解决方案”:

System.out.println((Integer.toBinaryString(
    new Random().nextInt()) + "00000000").substring(0, 8));

......除了略有偏见。包装线以便于阅读!

另外,请注意根据字面解释:

{ int tmp = new Random().nextInt(); /* add more statements here */ }

是一行代码。它甚至是一个Java语句: - )。

UPDATE :这是另一个没有偏见的版本:

System.out.println(Integer.toBinaryString(
    new Random().nextInt() | 0x80000000).substring(24));

强制符号位为1意味着我们不必担心前导零是否存在。