简体   繁体   中英

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!

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.

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:

b |= 1 << n;

if you want to unset a bit at index n , use:

b &= ~(1 << n);

Or use a BitSet (which has a convenient enough .flip() method).

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