I didn't study IT, and only very recently came across bit shifts and an application for two's complement. So, can you please use simple English in your explanations and assume I know hardly anything about IP addresses, bit operations, and Java datatypes?
Today, I found the following piece of code (abbreviated):
long m = (-1) << (byte) 16;
Now, this is for IP subnet masking. I know I need to start out with 4 blocks of 8 bits (i.e. 4 bytes), and all bits have to be "switched on": 11111111 11111111 1111111 1111111
Next, zeros are shifted in from the right, in this case 16 bits' worth; so we get 11111111 11111111 00000000 0000000
, the mask.
But I do have a few questions:
- Does the
16
have to be of typebyte
for this to work? - The result is of type
long
. When the expression above runs,-1
gets converted into - effectively - 4x8bit blocks. How does Java know it needs 32 positions/bits (an IP address' length), and not, say, 16, or 8, when applying two's complement? (I'm guessing that has to do with thelong
datatype?) - Why is two's complement applied to
-1
to begin with? (Google gives you-0b1
if you ask it what-1
is in binary. I first thought it might be to do with overflow, but it isn't, is it...?) - Really, what datatypes does the compiler convert this to while it's running the code, to make it all work?
UPDATE: The 16
is produced at runtime by a method; I just put a constant in here as an example. In hindsight probably a bad idea...
shl AX, 16
. At that level there aren't really data types. You just got blocks of 8, 16, 32 or 64 bits. – Strangeness