Rajat Gupta
Rajat Gupta

Reputation: 26597

Very simple question related to Java syntax

Could someone explain me what is the meaning of following symbols in the following line :

symbols | <<

long high = (System.currentTimeMillis() << 16) | 0x4000 | random.nextInt(4096);

How is the value of high calculated ?

Upvotes: 0

Views: 192

Answers (5)

RichardTheKiwi
RichardTheKiwi

Reputation: 107716

<< is used to shift bits, in this case left arrow for shifting left

| is used for bitwise-OR, which means given two operands, it will set the output bit position to 1 if either or both of the operands have a 1 in a particular position

System.currentTimeMillis() returns 32-bits, this shifts it to the left

xxxxxxxx yyyyyyyy zzzzzzzz aaaaaaaa
becomes
zzzzzzzz aaaaaaaa 00000000 00000000   (where the right bits are all 0's)

And the 0x4000

0x4000 in HEX = 01000000 00000000 in BINARY

random.nextInt(4096) produces an int just shy of 4096, so it can produce any combination of the bits

0000???? ????????   // where each ? can be randomly 0 or 1

So all in all,

  • how is the value of high calculated ?

It is made up of these components

zzzzzzzz aaaaaaaa 0100???? ????????  // binary representation of the long var (4 bytes)
  • z's and a's are the lower 16 bits from the current time
  • the 0100 is exactly that sequence
  • the 12 ?'s are generated randomly (0 or 1)

Upvotes: 2

Cesar Hermosillo
Cesar Hermosillo

Reputation: 942

The symbols are

| = or

<< = Bit shifting to the left

So basically the high value is a binary operation

Upvotes: 0

jhouse
jhouse

Reputation: 2692

"<< 16" means shift the bits of the value (currentTimeMillis) 16 positions to the left.

"| 0x400" means bitwise-OR that value with the bits 0x400

Upvotes: 1

joshcartme
joshcartme

Reputation: 2747

<< is a bitwise shift operator, you can read more about that here: http://www.sap-img.com/java/java-bitwise-shift-operators.htm.

| is the bitwise inclusive or which you can read more about here: http://www.roseindia.net/java/master-java/bitwise-bitshift-operators.shtml

Upvotes: 3

helloworld922
helloworld922

Reputation: 10939

<< is a bitwise shift operator. See: Java Tutorials: Bitwise and Bit Shift Operators

Upvotes: 2

Related Questions