jeudi 8 novembre 2018

random byte to int java

  1. In the Random class, define a nextByte method that returns a value of the primitive type byte. The values returned in a sequence of calls should be uniformly distributed over all the possible values in the type.
  2. In the Random class, define a nextInt method that returns a value of the primitive type int. The values returned in a sequence of calls should be uniformly distributed over all the possible values in the type. (Hint: Java requires implementations to use the twos-complement representation for integers. Figure out how to calculate a random twos-complement representation from four random byte values using Java’s shift operators.)

Hi I was able to do part 3 and now I need to use 3. to solve 4. but I do not know what to do. I was thinking of using nextByte to make an array of 4 bytes then would I take twos complement of each so I wouldn't have negative numbers and then I would put them together into one int. byte[] bytes = {42,-15,-7, 8} Suppose nextByte returns this bytes. Then I would take the twos complement of each which i think would be {42, 241, 249, 8}. Is this what it would look like and why doesn't this code work:

public static int twosComplement(int input_value, int num_bits){
    int mask = (int) Math.pow(2, (num_bits - 1));
    return -(input_value & mask) + (input_value & ~mask);
  }

Then I would use the following to put all four bytes into an int, would this work:

int i= (bytes[0]<<24)&0xff000000|
       (bytes[1]<<16)&0x00ff0000|
       (bytes[2]<< 8)&0x0000ff00|
       (bytes[3]<< 0)&0x000000ff;

Please be as specific as possible.




Aucun commentaire:

Enregistrer un commentaire