简体   繁体   English

Java如何将数组的位翻转为随机值

[英]Java How to flip bits of an array to random values

How could you create a method that could flip 2 bits (ranges 00-11 Hence 0-3) in a byte, Randomly! 您如何创建一种可以随机翻转2位(范围为00-11,因此为0-3)的方法!

Example 例

Coin flip one:   111 01 111
Coin flip two:   111 11 111
Coin flip three: 111 01 111
Coin flip four:  111 10 111

What I'm working with 我正在使用的

private static void coinFlip(byte theByte)
    {
        Integer mode = new Random().nextInt(3);
        byte value = mode.byteValue();
        byte tmp = value & 255;
            tmp = tmp >> 4;
            tmp = tmp & 3;
           //Point of confusion
           //Now stuff it back in index 5 & 4 ?
    }

Filling in using similar methods to what you are using, I think this should work: 使用与您所使用的方法类似的方法进行填写,我认为这应该可行:

private static byte coinFlip(byte theByte)
{
    //Get random value of form 000xx000
    Integer mode = new Random().nextInt(3);
    byte value = mode.byteValue();
    value = value << 3;
    //Mask the result byte, to format xxx00xxx
    byte mask = 231; //0b11100111
    byte maskedByte = theByte & mask;
    //return 000xx000 | xxx00xxx
    return maskedByte | value;
}

As fge said, though, BitSet is the saner way to do it. 正如fge所说,BitSet是更明智的方法。

Based on your code: 根据您的代码:

   private static byte coinFlip(byte theByte)
    {
        Integer mode = new Random().nextInt(3);
        byte value = mode.byteValue();
        return (byte)(theByte ^ (value << 3));
    }

Last line is simply XORING your byte with the two shifted random bits. 最后一行只是将您的字节与两个移位的随机位进行异或。

If you want to set a bit at index n , use: 如果要在索引n处设置一点,请使用:

b |= 1 << n;

if you want to unset a bit at index n , use: 如果要取消设置索引n的位,请使用:

b &= ~(1 << n);

Or use a BitSet (which has a convenient enough .flip() method). 或使用BitSet (具有足够方便的.flip()方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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