-1

I am trying to generate a random 16 bit number in java. I know how to generate random number for given range. can any one help how to generate a 16 bit random number

supraja
  • 85
  • 1
  • 7
  • Have you tried looking around? What have you found? And if you know the number is 16 bits, you can easily calculate the range... – awksp Jun 23 '14 at 05:53
  • Generate a random number and mask off 16 bits of it? - hey, it works ;-) – John3136 Jun 23 '14 at 05:54
  • If by range you mean a numeric range: http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java?rq=1 – Thilo Jun 23 '14 at 05:55
  • Do you mean `random.nextInt(1 << 16)` or `random.nextInt(1 << 16) + Short.MIN_VALUE;` – Peter Lawrey Jun 23 '14 at 06:24

2 Answers2

7

A 16 bit number a binary number with 16 digits. So it will be in the range

0000 0000 0000 0000 = 0
1111 1111 1111 1111 = 65535 (2^16-1)

So, you can do:

Random r = new Random();
r.nextInt(65536); // 65536 will not be considered, return integer in range [0,65535]

which, according to Java Docs, will

Return a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)...

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
3

Short is a 16bit

You can call Random class to generate random number on the range of Short.MAX_VALUE, which is around 0-65535. by adding the Short.MAX_VALUE and Short.MIN_VALUE

sample:

new Random().nextInt(1 + Short.MAX_VALUE - Short.MIN_VALUE);
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
  • This isn't right. First of all, the upper bound for `nextInt()` is *exclusive*. In addition, `Short.MAX_VALUE` is actually [32767](http://docs.oracle.com/javase/7/docs/api/java/lang/Short.html). – awksp Jun 23 '14 at 06:01
  • @user3580294 short min is 32768 and short max is 32767 two's compliment – Rod_Algonquin Jun 23 '14 at 06:02
  • That's true, but `nextInt()`'s upper bound is *exclusive*. So your method will never actually return 65535. Also, you forgot a close parenthesis. – awksp Jun 23 '14 at 06:03
  • I think you mean `1 + Short.MAX_VALUE - Short.MIN_VALUE` or just `1 << 16` – Peter Lawrey Jun 23 '14 at 06:27
  • @PeterLawrey same result. for your first sample. – Rod_Algonquin Jun 23 '14 at 06:28
  • @Rod_Algonquin But simpler. Your use of Math.abs() is flawed as it assumes MIN_VALUE must be negative, if it were positive, the range would be wrong, so lets just assume MIN_VALUE is negative. BTW using subtraction is also correct if MIN_VALUE were positive. – Peter Lawrey Jun 23 '14 at 06:32
  • BTW `1 << 15` works for 15 bits, and `1 << 17` works for 17 bits. It is more generic and simpler. – Peter Lawrey Jun 23 '14 at 06:33