简体   繁体   中英

Construct a byte from individual bits in java

I'm currently writing a random number generator that generates a pseudorandom int and then returns an int representing the least significant bit in the int value.

public class RNG {

    //algorithm input: first input is the seed
    private int x;

    //primes for calculating next random number
    private int p;
    private int q;

    //constructor
    public RNG()
    {
        p = getPrime();
        q = getPrime();

        //make sure p and q are not equal
        while(p == q)
        {
            q = getPrime();
        }

        //seed must not be divisible by p or q
        //easiest way is to make the seed another prime number
        //this prime does not need to be congruent to 3 mod 4, so
        //getPrime() is not used.

        x = (BigInteger.probablePrime(8, new Random())).intValue();
    }

    //return a pseudorandom prime number using java.util.Random such that
    //the number is congruent to 3 mod 4
    private int getPrime()
    {
        Random rand = new Random();
        int i;
        while(true)
        {
            //generates a random BigInteger. The probability
            //this BigInteger is composite is less than 2^-100
            //bitLength is 8 so maximum prime value is 251
            i = (BigInteger.probablePrime(8, rand)).intValue();
            if((i % 4) == (3 % 4))
            {
                break;
            }
        }

        return i;
    }

    public int next()
    {
        //calculate next algorithm input
        int next = (x * x) % (p * q);

        //set algorithm input for next next() call
        x = next;

        //return least significant bit
        return next & 1;
    }
}

The aim of the program is to be able to create a return value that a test class can then write to a file, and because the output is the least significant bit of the randomly generated number the output will be cryptographically secure.

However, when trying to come up with the implementation of the test class, I'm having trouble trying to figure out what to do with the output. What I need the test class to be able to do is write 512 bits to an output file. The FileOuputStream class, however, is only capable of writing bytes to the output file.

What I'm trying to do is figure out if there's a way to group the individual 1 or 0 outputs from my random number generator into byte values, but so far I've not found anything that's supported in Java.

You can construct bytes (or ints, or longs) using bit shifting with the << operator (or the bit shift and assignment operator <<= )

byte b = 0;
for (int i = 0; i < 8; i++) {
    b <<= 1;
    b |= rng.next();
}

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