-6

I'm wondering about this part of a code (it's an IP mask code)

int mask = 0xffffffff << (32 - prefix);
System.out.println("Prefix=" + prefix);
System.out.println("Address=" + ip);
int value = mask;
byte[] bytes = new byte[]{ 
(byte)(value >>> 24), (byte)(value >> 16 & 0xff), 
(byte)(value >> 8 & 0xff),
(byte)(value & 0xff) };
try {
InetAddress netAddr = InetAddress.getByAddress(bytes);
System.out.println("Mask=" + netAddr.getHostAddress());
YArt
  • 19
  • 1
  • 7
  • 3
    _"i wish that someone can put comments // after each line"_ SO is not a code translator service. What part is unclear? Did you search what does << do ? See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html – Alexis C. Dec 22 '14 at 21:52
  • 1
    possible duplicate of [Bitwise shift operators. Signed and unsigned](http://stackoverflow.com/questions/2244387/bitwise-shift-operators-signed-and-unsigned) – Palpatim Dec 22 '14 at 21:55

2 Answers2

4

<< is the Left Shift operator. >> is the Right Shift operator. You can read about bit shifting in Java here.

0xffffffff is an hexadecimal number.

zmbq
  • 38,013
  • 14
  • 101
  • 171
1

These are hexadecimal numbers and bitwise operations.

Hexadecimal numbers use a number system with radix 16. Thus 0xffff means:

(((15*16+15)*16+15)*16+15)*16+15=65'535

This is mainly useful because a nibble (one hexadecimal digit), maps exactly on four bits. Since F is 1111 in binary, 0xffff means 1111 1111 1111 1111 (or the last 16 bits are one).

<< and >> are bitwise arithmetic shifts. If you specify 0xffff<<8, it means you shift the number eight bits to the left thus:

     1111 1111 1111 1111                ff ff ff ff
<<                     8             <<           8
------------------------             --------------
1111 1111 1111 1111 0000             ff ff ff ff 00

>> is a shift in the opposite direction, but the highest bit also determines the value of the new bits at the left. In case the left bits should be zero, you need to use the logical right shift (>>>).

Other bitwise operations include |, &, ~ and ^ (not to be confused with &&, ||, etc.).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555