Getting an IP address using inetaddress gets a byte array
If you output this array directly, you will find that some bits in the IP address have become negative.
For example, 61.135.169.105 will be exported as 61.-121.-87.105.
Take a closer look and you'll find 135 + 121 = 256,169 + 87 = 256
-_-! What a situation!
The first thing I thought of was a problem with the byte type converting to type int, and later found that the actual failure
Because there is no unsigned type in Java, Byte, short, int, long are all signed, so there is no question of an implicit type conversion error at all.
Since the Java does not have unsigned type, then byte is 8 bits, so the range is 127-128, and IP a segment of the representation range of 0-255, finally found something wrong
A segment of IP is a unsigned byte, such a unsigned byte in a signed byte can cause some problems to occur
Analyze:
35 binary encoding is 1000 0111, the highest position is 1
Because byte is considered unsigned byte, so the highest bit of 1 will be interpreted as a sign bit, another Java storage is in accordance with the complement, so 1000 0111 will be considered as the complement form, converted to the original code is 1111 0001, converted to decimal number is-121.
Again, 65 of the binary code is 0100 0001, due to less than 128, so there is no maximum position 1,0100 0001 of the complement or 0100 0001, so 65 unchanged.
Analysis so much, the solution to this problem is actually very simple, the byte variable with the 0xFF bitwise and can, in the process byte implicitly type to int, when with 0xFF bitwise with, will all except the low 8 bits of other bits all 0, so that the symbol extension of those high level cleared off.
Finally, I enclose a common function written by myself to output the integer variable's binary code
Copy Code code as follows:
/**
* Output the integer variable as binary encoded form
* @param n-integer variable
* @param the binary length of the size integral type, which can be obtained using a similar short.size
* @return Binary encoded string
*/
public static String Printbinary (long n, int size) {
StringBuilder sb = new StringBuilder ();
for (int i = size-1 i >= 0; i--) {
Sb.append (n >>> I & 0x01);
if (i% 4 = 0) {
Sb.append ("");
}
}
return sb.tostring ();
}